Quantcast
Channel: PHP Freaks: PHP Help
Viewing all 13200 articles
Browse latest View live

Wordpress(woocommerce) help please?

$
0
0

Ok well turns out i didnt do it correctly. Supposedly i should have done it via the hook so it changed it on all pages where price was shown (common sense i guess). Now im a little stuck editing the get_price_html to include price per label. Anyone can see where im going wrong??

add_filter( 'woocommerce_get_price_html', 'chris_price_html', 100, 2 );
function chris_price_html( $price, $product ){
$priceperlabel = 'each';
//write logic to get the perlabel here

return str_replace( 'get_post_meta', 'get_post_id()'.$priceperlabel, $price );
}

Font Size Help

$
0
0

I have font size issue that seems like it should be simple to fix, yet I cannot find where to make the change, and if I have to use php or if I can use html.
 

It's in a very common web calendar ... Aptly named webCalendar ... and I'm hoping one of you is familiar with it or can figure out in the 5 minutes I thought it would take.

I took a screen shot and circled the problem text in red.

The page is located at http://www.nescotracing.com/events/month.php

 

nescotsmalltextissues.jpg

 

Do prepared statements expire?

$
0
0

For instance, if used in the following fictional script, they might be created and remain active for months at a time.  Is there any  concern about memory never being released, or anything other to watch out for?  Is this approach okay, or is one better creating the prepared statement, doing the work, and then closing it typical for most http request?

 

Thanks

$stmtSelect=$this->pdo->prepare('SELECT a, b, c FROM table_1 WHERE d=?');
$stmtInsert=$this->pdo->prepare('INSERT INTO table_1(a, b, c, d) VALUES(?,?,?,?)');
$stmtUpdate=$this->pdo->prepare('UPDATE table_1 SET a=?, b=?, c=? WHERE d=?');

$socket->on('connection', function (ConnectionInterface $conn) use($stmtSelect, $stmtInsert, $stmtUpdate) {
    $conn->on('data', function ($data) use ($conn) use($stmtSelect, $stmtInsert, $stmtUpdate) {
       $d=doSomething($data);
       if(someCondition) {
          $stmtSelect->execute([$d->a,$d->b,$d->c,$d->d]);
       }
       elseif(someOtherCondition{
           $stmtInsert->execute([$d->a,$d->b,$d->c,$d->d]);
       }
       else {
           $stmtUpdate->execute([$d->a,$d->b,$d->c,$d->d]);
       }
   });
});


//Script never gets here and it runs forever...

 

Login function not working correctly in CodeIgniter

$
0
0

Hello,

I've been working on a login system in which the function will check if three values on my database are equal to TRUE(1) or FALSE(0). So far I have an user account with the three values set to true so it should allow me to log in and redirect to the admin page but it does not. Can somebody help me with this, is there an error that I may be missing?
 
 

public function admin_login(){
 
//Check if logged in
$this->User_model->session_comprobate_admin();
 
//Set rules
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]');
 
 
        if ($this->form_validation->run() == FALSE) {
            //Load View Into Template
            $this->template->load('admin', 'login', 'users/login');
        } else {
            // Get Post Data
            $username = $this->input->post('username');
            $password = $this->input->post('password');
            $enc_password = md5($password);
            $data_user = $this->User_model->login($username, $enc_password);
// Verify variables
if($data_user){
            $user_id = $this->User_model->get_username($username);
            $users   = $this->User_model->get_userid($user_id);
 
//Check if active or banned
if($users->active == 0){
 
                // Create Error
                $this->session->set_flashdata('error', 'This account is banned or inactive.');
 
                // Redirect to pages
                redirect('admin/login');
 
}
 
//Check if is admin
if($users->is_admin == 0){
 
// Create Error
$this->session->set_flashdata('error' , 'Sorry, you can not access to this page.');
 
// Redirect
redirect('admin/login');
 
}
 
//Check if is member
if($users->is_member == 0){
 
// Create Error
$this->session->set_flashdata('error' , 'This account does not exists. Please try again.');
 
 
} else {
 
//Check if variables are true
                $user_data = array(
                    'user_id'   => $user_id,
                    'username'  => $username,
                    'is_admin' => true,
'active' => true,
'is_member' => true,
                );
 
                // Set Session Data
                $this->session->set_userdata( 'is_admin',$user_data);
$this->UserModel->is_admin($user_id);
 
                // Create Message
                $this->session->set_flashdata('success', 'You are logged in');
 
                // Redirect to pages
                redirect('admin');
}
} else {
                // Create Error
                $this->session->set_flashdata('error', 'Invalid Login');
// Redirect to pages
                redirect('admin/login');
}
}
}

 
This is my user_model info:

//I need to work on these two
    public function get_username($users) {
        $this->db->select('id');
        $this->db->from('users');
        $this->db->where('username', $users);
        return $this->db->get()->row('id');
    }


    public function get_userid($user_id) {
        $this->db->select('id');
$this->db->from('users');
        $this->db->where('id', $user_id);
        return $this->db->get()->row();
    }
///
//Check if admin
    public function is_admin($id) {
        $this->db->select('is_admin');
        $this->db->from('users');
        $this->db->where('id', $id);
        $is_admin = $this->db->get()->row('is_admin');
        if ($is_admin == 0) {
            redirect('/');
        } else {
            redirect('admin');
        }
    }


//Check if member
    public function is_member($id) {
        $this->db->select('is_member');
        $this->db->from('users');
        $this->db->where('id', $id);
        $is_member = $this->db->get()->row('is_member');
        if ($is_member == 0) {
            redirect('/');
        } else {
            redirect('dashboard/login');
        }
    }


//Check if active
    public function is_active($id) {
        $this->db->select('active');
        $this->db->from('users');
        $this->db->where('id', $id);
        $is_active = $this->db->get()->row('active');
        if ($is_active == 0) {
            redirect('/');
        } else {
            redirect('dashboard/login');
        }
    }
//Verify if username and email is already registered
    public function existent_username($username) {
        $query = $this->db->get_where('users', array('username' => $username));
        return $query->row_array();
    }
    public function existent_email($email) {
        $query = $this->db->get_where('users', array('email' => $email));
        return $query->row_array();
    }
//
    public function session_comprobate_member() {
        if ($this->session->userdata('is_member') != NULL) {
            redirect('dashboard');
        }
    }


    public function session_comprobate_admin() {
        if ($this->session->userdata('is_admin') != NULL) {
            redirect('admin');
        }
    }

It was working well but I just added the is_admin and is_member checks and it stop working..

Form radio buttons and drop down boxes not writing to database

$
0
0
Hi everyone! New to the group and also PHP coding.
What I have so far is 2 radio buttons and when or the other is ticked, it then displays its hidden drop down box to choose values. The radio buttons work correctly and show the proper drop down boxes but do not write correct values to the database!
 
I am trying to have the chosen radio box  called "INQUIRY" write a value of "1" to "IncidentType" column.
Or when the radio box called "COMPLAINT" is chosen, write a value of "2" to the same column.
It seems to always write "1" to the DB column regardless which radio box is ticked.
 
Also when the drop down box is chosen (which are populated from another DB column), I am looking for it to write the "complaint.ComplaintID" or the "inquiry.InquiryID" to the column "CaseTypeSubCategory" as the ID integer, which it does not.
 
I'm really stuck on solving this and would appreciate any help someone would be able to offer. I think my insert.php page has the correct values but if anyone would like to see it I will be happy to post the code.
Thank you in advance for replies! Here is my code so far for the page:
 
 
<html>
<head>
<style>
    #ca {
        display: none;
    }
</style>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
    $("input:radio").click(function() {
        $('.searchSelect').hide();
        $('#' + $(this).attr("value")).show();
    });
});
</script>
</head>
<body>
 
<form action="insert.php" method="post">
 
<?php
 
//Connect to our MySQL database using the PDO extension.
$pdo = new PDO('mysql:host=10.150.100.194:3308;dbname=publiccommenttracking', 'Iputmyusernameandpassword', 'inapublicpostontheinternet');
 
//Our select statement. This will retrieve the data that we want.
$sql = "SELECT complaint.ComplaintID, complaint.Description as Des, inquiry.InquiryID,Inquiry.Description as InquiryDescription
FROM complaint left join inquiry on complaint.ComplaintID = inquiry.InquiryID"; 
 
 
 
//Prepare the select statement.
$stmt = $pdo->prepare($sql);
 
//Execute the statement.
$stmt->execute();
 
//Retrieve the rows using fetchAll.
$users = $stmt->fetchAll();
 
?>
    <ul id="countrylist"> 
        <li> 
            <label for="US-country"> 
                <input name="IncidentType" type="radio" id="US-country" value="com" checked  /> 
                INQUIRY</label><input type="hidden" name="IncidentType" value="1">
       
      </li> 
        <li> 
            <label for="CA-country"> 
                <input name="IncidentType" id="CA-country" type="radio" value="ca"/> 
                COMPLAINT</label><input type="hidden" name="IncidentType" value="2">
        </li> 
    </ul> 
    <select name="CaseTypeSubCategory" id="com" class="searchSelect" title="Search in"> 
         <?php foreach($users as $user): ?> 
        <option value="<?= $user['inquiry.InquiryID']; ?>"><?= $user['InquiryDescription']; ?></option>
   <?php endforeach; ?> 
    </select>
    
     
    <select name="CaseTypeSubCategory" id="ca" class="searchSelect" title="Search in"> 
        <?php foreach($users as $user): ?> 
        <option value="<?= $user['complaint.ComplaintID']; ?>"><?= $user['Des']; ?></option>
   <?php endforeach; ?> 
    </select>
    
      <p><input type="submit" value="Submit"><br>
</form>
    
</body>
</html>

Statistics

$
0
0

New comer so do apologise if this is posted in the wrong place.

 

I'm working on a project that gathers the clients info (IP, Browser, Referral link and date+time of visit) which is then displayed in the browser in a html table,

I coded it so it wrote it to a txt file to check whether anything was happening (which it was) but i am now stuck on displaying it in a table.

 

Any help is appreciated!

Code below

 

<?php
 
$output = 'Log.txt'; /*This is the file where the data will be written to*/
 
@ $data = json_decode(file_get_contents("http://ipinfo.io/{$_SERVER['REMOTE_ADDR']}/json")); /*Gather the users IP and refer it over to the website which will return a json object which will be decoded and stored in $data*/
 
$filehandle = fopen($output, "a"); /*This opens the file declared in $output in append mode*/
if ($filehandle)
{
$string ='"'.$QUERY_STRING.'","'
.$_SERVER['REMOTE_ADDR'].'","' /*This writes the IP to the file*/
.$_SERVER['HTTP_USER_AGENT'].'","' /*This writes the users browser and OS to the file*/
.$_SERVER['HTTP_REFERER'].'","' /*This writes the the link that directed the user to this site to the file*/
.date("r").'"' /*This writes the date and time to the file*/
."\n"
;
$write = fputs($filehandle, $string);
fclose($filehandle);
}
?>
 
<html>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
border-spacing: 5px;
}
</style>
<h1>Statistics</h1>
<table width = "550px" height = "300px" border="1">
<tr bgcolour="#000000">
<th>IP address</th>
<th>Browser</th>
<th>Referrel URL</th>
<th>Date and Time</th>
</tr>
<tr>
<td>echo "$_SERVER['REMOTE_ADDR']"</td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
 
</html>

Attached Thumbnails

  • code.png

Error Handling: my code is working but I would like some in put on handling errors

$
0
0

I would like help bullet proofing my code. So if you could suggest ways to handle exceptions or on better ways to write the code I have I would be grateful.

 

 

<?php


$db= include('/var/app/app_env.php');





$port = 22;
$user = $db['cit_user'];
$pass = $db['cit_pass'];
$host = $db['cit_host'];
$connection = NULL;
$remote_file_path = "/Outbox/CCDATA.TXT";
$local_file = './cit_order_download'. date('mdY_hia') .'.co';
///////////////////////////////////////////////////////////////
//echo "<td>$host</td>";
///////////////////////////////////////////////////////////////
try {


    $connection = ssh2_connect($host, $port);
    if(!$connection){
        throw new \Exception("Could not connect to $host on port $port");
    }
    $auth  = ssh2_auth_password($connection, $user, $pass);
    if(!$auth){
        throw new \Exception("Could not authenticate with username $user and password ");
    }
    $sftp = ssh2_sftp($connection);
    if(!$sftp){
        throw new \Exception("Could not initialize SFTP subsystem.");
    }
    $stream = fopen("ssh2.sftp://" .(int)$sftp.'//Outbox//'.'CCDATA.TXT', 'r');
    $contents = stream_get_contents($stream);
    file_put_contents ($local_file, $contents);
    @fclose($stream);
    $connection = NULL;
  } catch (Exception $e) {
      echo "Error due to :".$e->getMessage();
  }


////////////////////////////////////////////////////////////////////////////////////////////////
$result_clear='';
$result_hold='';
$connect = odbc_connect($db['name'], $db['user'], $db['password']);
$approve_status=array("AA","AC","AD","AX");
$decline_status=array("DA","DR","HC","CI","CR","CZ");




sleep(2);
$fp    = fopen($local_file, 'r');
while (!feof($fp))
{
  $line  = fgets($fp);


  $order = substr($line, 69, 5);
  $status=substr($line, 117, 2);
  $assignment=substr($line, 91, 10);




  $order=ltrim(rtrim($order));




  if (in_array($status,$approve_status)){
   $file_array= array($order=> array($assignment,$status));
  $clear="update m1_kf.dbo.salesorders set uompcreditstatus='CLEAR', uompschedulecolor='$status$assignment' where ompsalesorderid ='$order' and ompOrderDate > '12-9-2017'";
echo $order,$assignment,$status;
echo "<br>";
$result_clear = odbc_exec($connect, $clear);
}
  elseif (in_array($status,$decline_status)){
$hold="update m1_kf.dbo.salesorders set uompcreditstatus='HOLD', uompschedulecolor='$status$assignment' where ompsalesorderid ='$order' and ompOrderDate > '12-9-2017'";
  echo $order,$assignment,$status;
echo"<br>";
$result_hold = odbc_exec($connect, $hold);
 }
}
fclose($fp);
odbc_close($connect);




?>

 

Allow variable rules on "Quantity Rules"

$
0
0

Hey guys, i need to Amend the quantity rules plugin to allow rules on product variations also.  Now I cant seem to find a way of doing this currently. I am still learning php/wordpress etc so its a bit above me at the moment. Im assuming i would need to add something in here? 

function wpbo_get_applied_rule( $product, $role = null ) {

	// Check for site wide rule
	$options = get_option( 'ipq_options' );

	if ( get_post_meta( $product->id, '_wpbo_deactive', true ) == 'on' ) {
		return 'inactive';

	} elseif ( get_post_meta( $product->id, '_wpbo_override', true ) == 'on' ) {
		return 'override';

	} elseif ( isset( $options['ipq_site_rule_active'] ) and $options['ipq_site_rule_active'] == 'on' ) {
		return 'sitewide';

	} else {
		return wpbo_get_applied_rule_obj( $product, $role );
	}
} 

 


I search function to show time like '1 hour ago'...

$
0
0

  Hello,
In my php7/vue.js2.5 application I use function from here https://gist.github.com/mattytemple/3804571
to show time like '1 hour ago', 'yesterday', 'tomorrow', 'in 2 weeks'

Bot looking at the comments, looks like it has some errors.
Now I need similar functions both in php and javascript with similar output results.

Please, share it is there are any...

Thanks!

html clickable link in a table result

$
0
0

I am in need of a way to make a field in a table show the table a clickable url.

 

 

Reading syslog/journalctl with PHP

$
0
0
I would like to allow an embedded webserver to view the server's system logs.  The PHP UX will allow user to:
  1. Select start/finish dates or select "real time" mode which will mimic journalctl -f.
  2. Select the user(s) who is logging the data similar to journalctl -u httpd.
  3. Optionally save the output in a file which will be downloaded to the webclient after the log is run (or canceled if using real time mode).
 
When a hard start and finish date is specified, my thoughts are probably to execute use exec() with journalctl with applicable flags including -o json, wrapping the data with HTML as required for viewing, and creating a CSV file for the optional file feature.
 
The real time mode will be a bit trickier.  Since this will not be continuously running but only on a as-needed basis, I would like to keep it simple.  Options for PHP to access the data seem to be:
  1. Directly reading sockets (sounds complicated).
  2. Directly read the log files (how?) and use http://php.net/manual/en/book.inotify.php to determine when it was changed (sounds complicated).
  3. cUrl requests to https://www.freedesktop.org/software/systemd/man/systemd-journal-gatewayd.service.html.  Security risk, however, I don't think it will ever be publicly accessible.
  4. Use http://php.net/manual/en/function.proc-open.php to create a stream.
  5. Call some sort of C library (sounds complicated)
  6. Something else?
 
And then there is implementing how the webclient can access the data.  Options seem to be:
  1. Bypass PHP and have the client directly query https://www.freedesktop.org/software/systemd/man/systemd-journal-gatewayd.service.html.
  2. Store the log obtained in one of the above strategies into a session, and have the client periodically poll the server using HTTP.
  3. Implement a websocket server.  I am only using a RPi, and am a little concerned about resources.
  4. Something else?
As you can likely tell, I haven't really vetted this out, and am really just looking for a general direction at this time.  Thanks!

Need help getting the script to search the database to find the record that matches the user's selection

$
0
0

Hi, I am trying to read in the name and student number that the user entered and compare it to what is in the mysql database. My teacher suggested using found. However I am still not getting anything to echo out. Can someone lead me in the right direction?

 

next.php

<?php
 
require 'connect.php';
 
//linking up to the database
$link = mysqli_connect(HOST, USER, PASS, DB) or die (mysqli_connect_error());
 
//making a variable from the user data
$name = mysqli_real_escape_string ($link, $_POST["name"]);
$number = mysqli_real_escape_string ($link, $_POST["snumber"]);
$course = $_POST["pcourse"];
 
// select all from table student which show student name and number
$squery = "SELECT * FROM students";
$sresult = mysqli_query($link, $squery);
 
while ($srow = mysqli_fetch_array($sresult)) {
 
  if ($name == $srow['uid'] && $number == $srow['student']) {
 
    if ($found) {
 
    echo "$srow[uid] $srow[student]";
 
    } else {
 
    echo "Student does not exist";
 
    }
  }
}
 
mysqli_close ($link);
?>
 
<html>
<body>
<form action="index.php" method="post">
  <br>
    <input type = "submit" value="back" name="back">
</form>
</body>
</html>
 
This is my index.php that I use as my form
 

<!DOCTYPE html>
<html>
  <body>
    <h1>Course Selection</h1><br>
 
 
    <form action="next.php" method="post">
 
 
              Name: <input type="text" name="name" placeholder="Name" required="required" maxlength="50">
              <br><br>
 
              Student Number: <input type="text" name= "snumber" required="required" maxlength="9">
              <br><br>
 
        <?php
        //form
      require 'connect.php';
 
      $link = mysqli_connect(HOST, USER, PASS, DB) or die(mysqli_connect_error());
 
      echo "Select a course: <select name = \"pcourse\">\n";
 
      $query = "SELECT * FROM course";
      $result = mysqli_query($link, $query);
 
      while ($row = mysqli_fetch_array($result)) {
        echo "<option> $row[code=auto:0] $row[name] $row[max]</option><br>";
      }
 
      mysqli_free_result($results);
 
      mysqli_close ($link);
 
      echo " </select>\n";
 
 
      ?>
 
      <br><br>
      <input type = "submit" value="submit" name= "submit">
 
    </form>
 
    </body>
    </html>

What's the best way to get a single record's info from multiple tables?

$
0
0

So I have two tables. 

 

Table 1 - Records

Table 2 - Earnings

 

I basically want to retrieve 6 active records from highest to lowest earnings.

 

Here are the table setups.

Records Table

record_id      |   record_name       |   status

1                   record_1                1
2                   record_2                0
3                   record_3                1
4                   record_4                1
5                   record_5                1
6                   record_6                1
7                   record_7                1
8                   record_8                1



--------------------------------------------

Earnings Table

earning_id     |    record_id     |    amount

1                      1               $100
2                      2               $200
3                      3               $300
4                      4               $400
5                      5               $500
6                      6               $600
7                      7               $700
8                      8               $800
9                      1               $100
10                     1               $100

As you can see I have total of 8 records. Only 7 of them are active. And record_1 has multiple earning rows. This is the tricky part. Normally I can retrieve the records seperatly and the earnings seperatly but I would like to know how can I combine this into a single query to achieve the same result so that I can list 6 active records from highest to lowest earnings?

 

Here is my way so far.

$find_records = $db->prepare("SELECT record_id, record_name, status FROM records WHERE status = :status");
$find_records->bindValue(':status', 1);
$find_records->execute();
$result_find_records = $find_records->fetchAll(PDO::FETCH_ASSOC);
if(count($result_find_records) > 0) {
  foreach($result_find_records as $row) {
    $record_id           =	$row['record_id'];
    $record_name         =	$row['record_name'];
    $record_status       =	$row['record_status'];

    $get_earnings = $db->prepare("SELECT amount FROM earnings WHERE record_id = :record_id");
    $get_earnings->bindParam(':record_id', $record_id);
    $get_earnings->execute();
    $result_earnings = $get_earnings->fetchAll(PDO::FETCH_ASSOC);
    if(count($result_earnings) > 0) {
      $ub = 0;
      foreach($result_earnings as $key=>$row) {
        $ub+= $row['deposit'];
      }
      $record_amount = $ub;
    }
  }
}

Creating a multidimensional array in a hierarchical form

$
0
0
So I am trying to list photo albums where each album contains individual photos. This is similar to categories where each category cotains posts.
I have two database tables, namely "albums" and "photos". 
The albums table has columns id, album_name, and album_description.
The photos table has columns id, photo_is_in, photo_name and photo_description.
 
I used INNER JOIN to combine  the albums and photos table to produce the flat $albums array below: 
 
<?php

$albums  = [
['album_id' => '1', 'photo_id' => '41', 'album_name' => 'album_1', 'album_description' => 'Album 1 description', 'photo_is_in' => 'album_1', 'photo_name' => 'photo_1.jpg', 'photo_description' => 'Photo 1 description'],

['album_id' => '1', 'photo_id' => '42', 'album_name' => 'album_1', 'album_description' => 'Album 1 description', 'photo_is_in' => 'album_1', 'photo_name' => 'photo_2.jpg', 'photo_description' => 'Photo 2 description'],

//==================

['album_id' => '2', 'photo_id' => '43', 'album_name' => 'album_2', 'album_description' => 'Album 2 description', 'photo_is_in' => 'album_2', 'photo_name' => 'photo_3.jpg', 'photo_description' => 'Photo 3 description'],

['album_id' => '2', 'photo_id' => '44', 'album_name' => 'album_2', 'album_description' => 'Album 2 description', 'photo_is_in' => 'album_2', 'photo_name' => 'photo_4.jpg', 'photo_description' => 'Photo 4 description'],

];

?>


I want to turn the $albums array above into a hierachical array like below:
 
<?php

$sameAlbums = Array(

	'album_1' => Array( //comes from 'album_name' => 'album_1' in the $data array above
		'album_id' => '1',
		'album_description' => 'Album 1 description',
		'album_1' => Array( //comes from 'phot_is_in' => 'album_1' in the $data array above

			'photo_1.jpg' => Array(
				'photo_id' => '41',
				'photo_description' => 'Photo 1 deescription',

			),


			'photo_2.jpg' => Array(
				'photo_id' => '42',
				'photo_description' => 'Photo 2 deescription',

			)


		)

	),

	//============================================

	'album_2' => Array( //comes from 'album_name' => 'album_2' in the $data array above
		'album_id' => '2',
		'album_description' => 'Album 2 description',
		'album_2' => Array( //comes from 'phot_is_in' => 'album_2' in the $data array above

			'photo_3.jpg' => Array(
				'photo_id' => '43',
				'photo_description' => 'Photo 3 deescription',

			),


			'photo_3.jpg' => Array(
				'photo_id' => '44',
				'photo_description' => 'Photo 4 deescription',

			)


		)

	)

);

?>

I have tried something like this which did not work as expected and I need help here:

<?php
$grouping = [];
foreach($albums as $albumName){
	//Grouping data by album name
	$grouping[$albumName['phot_is_in']] = $albumName[];
}

echo "<pre>";
echo print_r($grouping);

?>

 

 

How to use select2 in CodeIgniter and how to implode the values inserted on it.

$
0
0

Hello,

so I've been trying to use Select 2 in the AdminLTE template with a function in javascript to add dynamic data.

 

Capture3.jpg

 

 

Here is my view in which I'm using a form_input with a class of select2.:

            <div class="form-group">
                <?php echo form_label('Skills', 'skills'); ?>
                <div class="input-group date"><div class="input-group-addon"><i class="fa fa-star" aria-hidden="true"></i></div>
                <?php
                    $data = array(
                        'name'          => 'skills',
                        'id'            => 'skills',
                        'class'         => 'form-control select2',
						'style'			=> 'width:100%',
                        'value'         => $item->skills
                    );
                ?>

                <?php echo form_input($data); ?>
                </div>
            </div>

and here is the script which should allow me to add the skills:

$(".select2").select2({
    tags: true,
    tokenSeparators: [',', ' ']
})

Is it supposed to set the tags equal to TRUE allow me to add data? Because what I know the input when adding a new content should turn into a blue color, right?. It is not doing it.

 

 

SECOND PART

Now can somebody help me in how to correctly implode(separate by comma) the skills into my database?. I actually though that in was by just doing something like:

$user_skill = implode(' , ' , $this->input->post('skills'))

and then passing the data to the database users with:

'skills' => $user_skills,

but it is not working and I really don't know why(it's sending nothing to the database). It does not update my users.id; here is a pic:

Capture.jpg

    public function edit($id){

        // Check Login
        if (!$this->session->userdata('is_member')) {
            redirect('dashboard/login');
        }

		// Field Rules
        $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|min_length[2]');
        $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|min_length[2]');
        $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|min_length[7]|valid_email');

        if ($this->form_validation->run() == FALSE) {
            // Get Current Subject
            $data['item'] = $this->User_model->get($id);
            //Load View Into Template
            $this->template->load('public', 'default', 'users/edit', $data);
        } else {
            $slug = str_replace(' ', '-', $this->input->post('username'));
            $slug = strtolower($slug);

			$user_skills = implode(',', $this->input->post('skills'));
            // Create User Data Array
            $data = array(
                'first_name' => $this->input->post('first_name'),
                'last_name'  => $this->input->post('last_name'),
                'email'      => $this->input->post('email'),
                'username'   => $this->input->post('username'),
				'slug'		 => $slug,
				'avatar_img' => $this->input->post('avatar_img'),
				'cover_img' => $this->input->post('cover_img'),
				'genre' => $this->input->post('genre'),
				'company' => $this->input->post('company'),
				'phone' => $this->input->post('phone'),
				'address' => $this->input->post('address'),
				'occupation' => $this->input->post('occupation'),
				'biography' => $this->input->post('biography'),
				'website' => $this->input->post('website'),
				'birthdate' => $this->input->post('birthdate'),
				'interested_in' => $this->input->post('interested_in'),
				'college' => $this->input->post('college'),
				'highschool' => $this->input->post('highschool'),
				'skills' => $user_skills,
            );

            // Update User
            $this->User_model->update($id, $data);

            // Activity Array
            $data = array(
                'resource_id' => $this->db->insert_id(),
                'type'        => 'user',
                'action'      => 'updated',
                'user_id'     => $this->session->userdata('user_id'),
                'message'     => '(' . $data["username"] . ') Updated his/her information'
            );

            // Add Activity
            $this->Activity_model->add($data);

			// User Skills Array
			$data = array(
				'id' => $this->db->insert_id(),
				'skills' => $user_skills,
			);

			// Add User Skill
			$this->Skills_model->add($data);

            //Create Message
            $this->session->set_flashdata('success', "You're account has been updated");

            //Redirect to Users
            redirect('dashboard/profile');
        }
    }

Fetching the skills in the view would be something like this or do I need to do a different approach. 

<?php echo $this->session->skills; ?>

THIRD PART

 

Also I would like to know if somebody knows how to add skills to a database table depending on the skills added by the user on his account?

 

As you can see in the controller I created something like:

 

// User Skills Array
$data = array(
'id' => $this->db->insert_id(),
'skills' => $user_skills,
);


// Add User Skill
$this->Skills_model->add($data);

How can I make sure that all the data inside the variable $user_skill fits into my user_skills table. I mean the table should be increasing its rows according to the number of skills added by the users.

 

Capture2.jpg

 

I hope somebody can helps and understand what I mean. Thanks.


Couldn't Resolve Host (cURL)

$
0
0
Hello. I'm fairly new to PHP, and unfortunately the specificity of my problem means I have to just ask about it: I am using Eventbrite's API and cURL, pulling data into a table (formatted through DataTables) and I am getting this "Couldn't resolve host" error, for approximately the first 11 pages, at which point I am presented with the data formatted as expected.
Here is the result: https://tinyurl.com/yde49f3d
Any help is much appreciated, this one has me beat-down and put my junior-level programmer ego in check!
And here is the back-end code: https://pastebin.com/pCSkU6UQ
Note: function u() and function h() are urlencode() and htmlspecialchars(), respectively. Thanks!
Edit: Realized I wouldn't click the link to look at code in another tab, so here's the code directly:
<table id="events" class="display compact" width="100%">
<thead>
<tr>
<th>Event ID</th>
<th>Event Name</th>
<th>Location</th>
<th>Description</th>
<th>Link</th>
<th>Time</th>
<th>Date</th>
<th>Add Event</th>
<th>View Attendees</th>
</tr>
</thead>
<tbody>

<?php

$token = "IPUTMYAPITOKENINTOAPUBLICPOSTONTHEINTERNET";
$pageNumber = 0;
$continuationToken = "";

$curl = curl_init();

curl_setopt_array($curl, array(CURLOPT_URL => "https://www.eventbriteapi.com/v3/users/me/owned_events/?token=IPUTMYAPITOKENINTOAPUBLICPOSTONTHEINTERNET",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$urlloop = u(h('https://www.eventbriteapi.com/v3/users/me/owned_events/?'));

$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
// Stores the json response data in an array
$array = json_decode($response, true);
}
?>
<?php

for($i = 0; $i < $array["pagination"]["page_count"]; $i++) {
if($array["pagination"]["has_more_items"] === true) {
for($j = 0; $j < $array["pagination"]["page_size"]; $j++) {

$continuationToken = $array["pagination"]["continuation"];
$newurl = '"';
$newurl .= $urlloop;
$newurl .= "continuation=";
$newurl .= $continuationToken;
$newurl .= "&token=";
$newurl .= $token;
$newurl .= "&page=";
$newurl .= $pageNumber;
$newurl .= '"';
curl_setopt_array($curl, array(CURLOPT_URL => $newurl,
CURLOPT_CUSTOMREQUEST => "GET"));
$response = curl_exec($curl);

$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {

$array = json_decode($response, true);
}
$event_id = $array['events'][$j]['id'];
$event_name = $array['events'][$j]['name']['text'];
$location = $array['events'][$j]['venue_id'];
$description = $array['events'][$j]['description']['text'];
$link = $array['events'][$j]['url'];
$time = $array['events'][$j]['start']['local'];
$date = $array['events'][$j]['start']['local'];
?>

<tr><td><?php echo($event_id);?></td>
<td><?php echo ($event_name);?></td>
<td><?php echo ($location);?></td>
<td><?php echo ($description);?></td>
<td><?php echo ($link);?></td>
<td><?php echo ($time);?></td>
<td><?php echo ($date);?></td>
<td><a href=<?php echo 'add-events.php?id=' . $event_id . '&name=' . h(u($event_name)) ?>><button class="btn btn-default btn-md">Add Event</button></a></td>
<td><a href=<?php echo 'show-attendees.php?id=' . $event_id . '&name=' . h(u($event_name)) ?>><button class="btn btn-default btn-md">View Attendees</button></a></td></tr>

<?php
}
}
$pageNumber++;
}
?>
</tbody>
</table>
<script>

$('#events').dataTable( {
"autoWidth": false,
"columns": [
{ "width": "5%" },
{ "width": "10%" },
{ "width": "5%" },
{ "width": "75%" },
{ "width": "5%" },
]
} );
</script>

<?php curl_close($curl); ?>
<?php
include_once('footer.php');
?>
</body>

Help: Unable to get a student written to database more than once

$
0
0

Hi, I am almost done my assignment however I am having an issue. I am trying to read enrolment and if the student is already registered for the course then print an error. However I am only able to register one student in one course each before getting the error message, which leads me to believe that it isn't reading the enrolment file properly. I seam to have an issue with this. Any help would be grateful. Thank you

 

// if the course is found and the student is found then check if they have registered
if ($found==3) {


  $equery= "SELECT * FROM enrolment WHERE uid ='$number' AND code = '$course'";
  $eresult= mysqli_query($link, $equery);


  while ($erow = mysqli_fetch_array($eresult)) {
  if ($erow['code'] == $course && $number == ($erow['uid'])) {


  
    } // if ($erow['code'] == $course && $number == ($erow['uid']))
  } // while ($erow = mysqli_fetch_array($eresult))
} // if ($found==3)


//if the student isn't registered in the course


$equery = "INSERT INTO enrolment(uid,code) VALUES ('$number','$course')";


if (mysqli_query($link, $equery)) {
  echo "New record created successfully";
}// if (mysqli_query($link, $equery))
else {
  echo "Error: You have already registered for the course";
} // else echo "Error: " .$link->error;


mysqli_close ($link);

 

If not available else function

$
0
0

Hi,

 

i have a issue with a booking plugin in Wordpress. If a room is booked, it is showing the room in search results just with a "NOT AVAILABLE" label. From a UX perspective it is a better option to not show it at all if the room is booked.

 

I found the code controlling the issue:

//available or not
if ( nd_booking_is_qnt_available(nd_booking_is_available($nd_booking_id,$nd_booking_date_from,$nd_booking_date_to),$nd_booking_date_from,$nd_booking_date_to,$nd_booking_id) == 1 ) {
    $nd_booking_availability = "";
}else{
    $nd_booking_availability = "<span class='nd_options_color_white nd_booking_font_size_10 nd_booking_line_height_10 nd_booking_letter_spacing_2 nd_booking_padding_3_5 nd_booking_top_10 nd_booking_position_absolute nd_booking_right_10 nd_booking_bg_yellow'>".__('NOT AVAILABLE','nd-booking')."</span>";
}

I tried a few options but allways generate a blank page. Any idea what should be written after "else" so that the booked room won't show at all in search results.

 

Cheers.

 

Send customer order email

$
0
0

I need a fresh set of eyes. This is the link to the website: http://hermanshivehire.biz/index.php

Basically its purpose is to send an email to a customer summarizing their order.

 

The issue I'm having is with the foreach statement . When the email is sent to admin - an email is sent for each product item.

The figures and totals are all correct.

I have tried closing the foreach in different places and this results is one email but there is no loop for the product items.

 

Here is my code (you can copy it into notepad++):

<?php
                $member_id = $_SESSION['memberID'];
                $query = "INSERT INTO tbl_order (orderDate, order_memberID_F) VALUES (NOW(), '$member_id')"; // $orderDate = datetime(now);
                mysqli_query($link, $query);
                // retrieve the order id from tbl_order
                $orderID = mysqli_insert_id($link);
                // decode product id from $_SESSION['cart']
                $cart = $_SESSION['cart'];
                $items = explode(',', $cart);  // $items is an array now
                $content = array();  // declares $content as array
                foreach ($items as $productID) {
                    if (isset($content[$productID]))
                        $content[$productID] = $content[$productID] +1;
                    else
                        $content[$productID] = 1;
                        // $content[$productID] = (isset($content[$productID]))?$content[$productID] + 1:1; SHORTENED VERSION OF ABOVE IF
                } // end of foreach
                // store $content into tbl_order_product
                foreach ($content as $product_id=>$qty) {
                    // retrieve product price AND name from tbl_product
                    $query = "SELECT * FROM tbl_product WHERE productID ='$product_id' ";
                    $result = mysqli_query($link, $query);
                    $row = mysqli_fetch_array($result);
                    $price = $row['price']; //value from database
                    $prodName = $row['name']; //value from database
                    $total = $qty*$price;
                    $grandTotal = $grandTotal + ($qty*$price);
                    $query = "INSERT INTO tbl_order_product (orderID_F, productID_F, orderQuantity, orderPrice)  VALUES ('$orderID', '$product_id', '$qty', '$price')";
                    mysqli_query($link, $query);
                    unset($_SESSION['cart']); // destroys the cart session
                } // end of foreach

                    //send email TO admin WITH ORDER DETAILS
                    $email_to = "info@hermanshivehire.biz"; // your email address send TO
                    $email_from = "info@hermanshivehire.biz"; // your email address send FROM
                    $subject = "RE: New Website Order to Fulfill";

                    // From
                    $header = 'From: '.$email_from."\r\n".
                    'Reply-To: '.$email."\r\n" ;

                    // email message content
                    $message="\n
                    Hi Rebecca and Craig! \n
                    There is a new order to fulfill.\n
                    Please contact them to arrange payment.\n
                    The order as follows:
                _______________________________________________________________________

                    Name: $custName
                    Email: $email
                    Address: $address
                    Phone: $phone

                    OrderID: $orderID
                    Product name: $prodName
                    Order quantity: $qty
                    Order price: $$price each
                    Total: $$total.00
                    Grand Total: $$grandTotal.00

                _______________________________________________________________________
                    Warm regards,\n
                    Hermans Hive Hire
                    ";

                    //send email
                    $sentMailAdmin = mail($email_to, $subject, $message, $header); // mail() to admin email
?>

Your assistance is much appreciated!

REST API protect

$
0
0

Hi,

 

I've created a REST API to provide several services to the users. Each one has an username, password and a api key, which is secret - it can only be decrypted by me.

 

My problem is that one of the apps is for the user load a webpage and retrieve info from its calculations (whic calls a api script).

 

For now the system I'm using is this:

 

1) First, the user must write the current time to a file in his domain.

2) The user sends to the api the current url (that must match my database ip info) along with a value equal to the api key + time

3) In my side, I fetch the file that must reside in the url he sent - which must match the domain ip registered by him - and the difference in time can't be more than 5 seconds.

4) I generate a session token which includes his api key plus time (encrypted) again and send it to him.

5) The request page is loaded with the api key and session token as hidden fields that when runned must match again the info I have.

 

Can someone please advise on the refinement of this logic? Do I maintain the token for 5,10, or 30 minutes? Or do I change it in every request?

 

Kind regards

 

Kepler

Viewing all 13200 articles
Browse latest View live