Jump to content

Search the Community

Showing results for tags 'mysqli'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...

Date Created

  • Start


Last Updated

  • Start


Filter by number of...


  • Start





Website URL








Donation Link

  1. Hey, Wrote I quick script to filter results from database. It kinda works but not sure if this is best or even secure way to do it. I know mysqli has function 'bind_params', but failed to make it work. <form action="" method="get"> <input type="checkbox" name="data" value="3" /> <input type="submit" /> <?php if( empty($_GET['data']) ) { die("GET empty"); } $mysqli = new mysqli('localhost', 'user', 'password', 'database'); $statement = "SELECT * FROM table1 WHERE id=" . $_GET['data']; $result = $mysqli->query($statement); while( $row = $result->fetch_assoc() ) { echo $row['id']; echo "<br/>"; echo $row['text']; if ($row['img'] != NULL) echo "<img src=" . $row['img'] . " > "; } ?> So just basic checkbox interface, when selected one of checkboxes and submitted, script queries database with matching ID from GET, returns results and loops through them. Inside loop checks for associated image src, if not present ignores field. I want to use this fucntions logic in my project but not sure if secure nor best/easiest way to do this. Obviously will improve interface, naming of variables etc.
  2. Hello Forumites!! I would like to ask a bit of advice please. I am currently writing a peice of code where my user can add content to their database and retreive it from the database when they view it live on the website. I want them to be able to edit their content and this my friends is wherein the problem lies. This is my Edit code: <?php function editnews($i) { $conn = mysqli_connect("Connection Stringy Stuff"); $enquery = "SELECT * FROM news WHERE newsid=$i"; $enresult = mysqli_query($conn, $enquery) or trigger_error("Query Failed! SQL: $conn - Error: ".mysqli_error(), E_USER_ERROR); while ($enrow = mysqli_fetch_array($enresult)) { echo " <form enctype='multipart/form-data' action='newsedit.php' method='post'> <table> <tr> <td>News Ref:</td> <td>" . $i . "<input type='hidden' name='newsid' value='" . $i . "' /><input type='hidden' name='oldim' value='" . $enrow['newsimage'] . "' /></td> </tr> <tr> <td>Title:</td> <td><input type='text' name='title' value='" . $enrow['newstitle'] . "' size='100' /></td> </tr> <tr> <td>Author:</td> <td><input type='text' name='author' value='" . $enrow['newsauthor'] . "' size='100' /></td> </tr> <tr> <td>Status:</td> <td><select name='stat'><option value='enabled' "; if ($enrow['newstatus'] == "enabled") { echo "selected='selected' "; } echo ">Enabled</option><option value='disabled' "; if ($enrow['newsstatus'] == "disabled") { echo "selected='selected' "; } echo "}>Disabled</option></select> </td> </tr> <tr> <td>Snippettext:</td> <td><textarea name='snip' rows='6' cols='80'>" . $enrow['newssnippet'] . "</textarea></td> </tr> <tr> <td>News story:</td> <td><textarea name='stry' rows='20' cols='80'>" . $enrow['newsarticle'] . "</textarea></td> </tr> <tr> <td>Current image:</td> <td>" . $enrow['newsimage'] . " - <a href='news/" . $enrow['newsimage'] . "' target='_blank'>View Image</a></td> </tr> <tr> <td>Change Image:</td> <td><input type='file' name='file'></td> </tr> <tr> <td colspan='2'><input type='submit' name='submit' value='Edit' /></td> </tr> </table> </form> "; } } ?> This code displays on the 'Edit' page using the following above the DOC type: <?php include('functions/newseditform.php'); $i = $_GET['i']; ?> AND the following in the HTML: <?php editnews($i) ?> The problem I have however is that the code at the top, does not actually display anything on the html page I have debugged the code in my IDE and received these error messages: Notice: Undefined index: i in pathway on Line 3 (This is the bit at the top of the 'Edit' page) AND Catchable fatal error: Object of class mysqli could not be converted to string in 'pathway' on line 8 this being this line of the edit code: $enresult = mysqli_query($conn, $enquery) or trigger_error("Query Failed! SQL: $conn - Error: ".mysqli_error(), E_USER_ERROR); Before I added the 'trigger_error' bit, it was displaying the "Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given" error. If anyone can help point out where I went wrong I would be very appreciative. Thanks!!!
  3. I've been banging my head on a wall for 30 hours over this! What I am trying to do seems so simple. I have a couple of views, a profile overview type of page and an edit profile page. After verifying your account with an email link my site brings you to a blank-ish profile page and you have to follow another link from there to update your profile. It's just not as slick as I'd like it to be before launch and allows other functionality to be available before your profile has any content. I don't like it. I created a specific "Create Your Profile" view that I want to include only if a user_id hasn't been included in the profilemaster table. All that I have left to do is check to see if my session user_id exists in my profilemaster table and if it does include the old profile page and if it doesn't include the new "Create Your Profile" page. I have tried everything over and over and then got beat up by the people at stack on top of it. I need some direction. I might just be tired, I've been working on the site for a solid week. All of my other functions are working, data can be inserted and updated, my emails are flowing when they need to, my log in is safe. I'm befuddled. Thanks if you have any suggestions! Justin
  4. i want to retrieve username from database table and display it where i put the code $username , i'm using the following code to make it work but its giving me an error : <?php require_once("models/config.php"); if (!securePage($_SERVER['PHP_SELF'])){die();} require("models/db-settings.php"); $mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name); $result = $mysqli->query("SELECT user_name FROM upl_users"); // This will move the internal pointer and skip the first row, we don't want that. //$row = mysql_fetch_assoc($result); //echo $row['user_name']; while ( $row = $result->fetch_assoc() ) { $username = $row['user_name'];} $dir = 'uploads/$username/'; if (file_exists($UploadedDirectory)) { mkdir('uploads/$username/', 0777, true); } if(isset($_FILES['FileInput']) && $_FILES['FileInput']['error']== UPLOAD_ERR_OK) { ############ Edit settings ############## $UploadDirectory = 'uploads/$username/'; //specify upload directory ends with / (slash) ########################################## /* Note : You will run into errors or blank page if "memory_limit" or "upload_max_filesize" is set to low in "php.ini". Open "php.ini" file, and search for "memory_limit" or "upload_max_filesize" limit and set them adequately, also check "post_max_size". */ //check if this is an ajax request if (!isset($_SERVER['HTTP_X_REQUESTED_WITH'])){ die(); } //Is file size is less than allowed size. if ($_FILES["FileInput"]["size"] > 5242880) { die("File size is too big!"); } //allowed file type Server side check switch(strtolower($_FILES['FileInput']['type'])) { //allowed file types case 'image/png': case 'image/gif': case 'image/jpeg': case 'image/pjpeg': case 'text/plain': case 'text/html': //html file case 'application/x-zip-compressed': case 'application/pdf': case 'application/msword': case 'application/vnd.ms-excel': case 'video/mp4': case 'audio/mp3'; break; default: die('Unsupported File!'); //output error } $File_Name = strtolower($_FILES['FileInput']['name']); $File_Ext = substr($File_Name, strrpos($File_Name, '.')); //get file extention $Random_Number = uniqid(); //Random number to be added to name. $NewFileName = $Random_Number.$File_Ext; //new file name if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName )) { die(' Success! File Uploaded.'); }else{ die('error uploading File!'); } } else { die('Something wrong with upload! Is "upload_max_filesize" set correctly?'); } ?> error: it creates the folder named : $username and not retirieves it from database , if i'm logged in and i upload a file then script need to create a folder with my name : admin ; uploads/admin/file.jpg but it makes ; uploads/$username/file.jpg any help thanks in advance
  5. Hello Everyone,I was learning connecting MySQLi with PHP.I wanted to display the names of all the databases on my server.I used the following code. <?php $server = 'localhost'; $user = 'root'; $pass = 'pass'; $mysqli = new mysqli($server,$user,$pass); if($mysqli->connect_error) die("Could not connect to server.<br/>"); $query = "SHOW DATABASES"; if($result = $mysqli->query($query)) { while($row = $result->fetch_row()) { printf("%s<br/>",$row[0]); } } ?> I am getting the desired result,but I didi not understand the functions fetch_row() and fetch_assoc properly. and why are we using the indice '0' in the line printf("%s<br/>",$row[0]); I tried using 1,but it gave me errors.I did not understand what was given on php.net manual. Someone please explain me in detail. Thank you.
  6. I am having a minor problem with my code if any one can help. I have a form where the user can add a new article however on submit this error is displayed: Warning: mysqli_query() expects parameter 1 to be mysqli, object given in //public_html/admin/includes/addnews.php on line 12. This is the code: $auth = $_POST['auth']; $tit = $_POST['tit']; $stat = $_POST['stat']; $shrt = $_POST['short']; $art = $_POST['art']; $conn = mysqli_connect("localhost","db","password","db") or die ("Could not connect to database"); $query = $conn->prepare ("INSERT INTO newsitem (author,title,shortdesc,article,newsdate,status) VALUES ('$auth','$tit','$shrt','$art',CURDATE(),'$stat')"); $result = mysqli_query($query,$conn); if($result){ echo "successful"; echo "<BR>"; echo "<a href='news.php'>Back to News </a>"; } else { echo "error could not upload article"; } mysqli_close($conn); ?> I have been looking at this for the last two hours with no hope, is there anyone who can point me in the right direction please?
  7. Can anyone enlighten me I just went to php.net and search for mysqli_close says it does not exist?? mysqli_close($db_con); I have been using this to try to close a connection any advice?
  8. hi, I tried to change update query from mysql to mysqli, at first under mysql is works great to update into mysql database but when i changed to mysqli is not doing update it. can anyone tell me what did i missed! under mysql <?php include('db.php'); if(isset($_GET['status'])) { $status1=$_GET['status']; $select=mysql_query("select * from manage where id='$status1'"); while($row=mysql_fetch_object($select)) { $status_var=$row->status; if($status_var=='0') { $status_state=1; } else { $status_state=0; } $update=mysql_query("update manage set status='$status_state' where id='$status1' "); if($update) { header("Location:index.php"); } else { echo mysql_error(); } } ?> <?php } ?> and under mysqli <?php include('db.php'); $dbcs = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database); if(isset($_GET['status'])) { $status1=$_GET['status']; $sql = "select * from product where product_id='$status1'"; $result=mysqli_query($dbcs,$sql); while($row=mysqli_fetch_object($result)) { $status_var=$row->status; if($status_var=='0') { $status_state=1; } else { $status_state=0; } $mysqli->query("UPDATE product set status='$status_state' where product_id='$status1' "); if($mysqli) { header("Location:item.php"); } else { echo mysqli_error(); } } ?> <?php } ?>
  9. I am having a problem understanding why when I run my script and I put the results inside a select statement it does not show the values but when I remove the select statement the values or visible . The following code will show you what I mean. If you comment out the select statement in the html script it will work. I don't understand way <?php // CONNECT TO THE DATABASE $DB_NAME = 'notary'; $DB_HOST = 'localhost'; $DB_USER = 'root'; $DB_PASS = ''; $db=$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } ?> <?php include("db.php"); $sql='SELECT * FROM customer'; $result=$db->query($sql); while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) { echo "<option value=" . $row['name'] . ">" .$row['name'] . "</option>"; } <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>ready demo</title> <script src="js/jquery.js"></script> <script> $( document ).ready(function() { $.ajax({ //create an ajax request to load_page.php type: "GET", url: "php/display.php", dataType: "text", //expect html to be returned success: function(response){ $("#responsetext").text(response); //alert(response); } }); /*$( "p" ).text( "The DOM is now loaded and can be manipulated." );*/ }); </script> </head> <body> <div align="center"> <select name="customer"> <!--<---comment out this line--> <div id="responsetext"> </select> <!--<---comment out this line--> </div> </body> </html>
  10. I am trying to be good and re-write all of my scripts to use mysqli instead of mysql_query & mysql_result etc. I have written the code below, but I am stuck. Here's an explanation: while($row = $result->fetch_assoc()){ echo $row['col_1'] ; } results echo's "ON" or "OFF" based on the settings of another app. I want to assign that result (ON or OFF) to a variable $status. I will then use that to do something else: if ($status == 'OFF' ) $display_this = 'on.gif' ; if ($status == 'ON' ) $display_this = 'off.gif'; Here is the code I have written so far: <?php include "database_login.php"; $db = new mysqli('localhost', $username, $password, $database); if($db->connect_errno > 0){ die('Unable to connect to database [' . $db->connect_error . ']'); } $sql = <<<SQL SELECT * FROM `ft_data_18` SQL; if(!$result = $db->query($sql)){ die('There was an error running the query [' . $db->error . ']'); } while($row = $result->fetch_assoc()){ echo $row['col_1'] ; } $db->close(); ?>
  11. I can't seem to get reliable results after deleting a row(s) using mysqli. The afftect_rows is always 0. I'm using php5.2 and the mysqli method Something like this: $sql = " DELETE FROM classRoster WHERE id=123 "; if ($result = $this->mysqli->query($sql)) { return $this->mysqli->affected_rows; ///ALWAYS RETURNS 0 }else{ //log error } I have confirmed that the row is in fact deleted, but still get 0 as affected_rows. Please help!
  12. Hello, I'm coding a log in page and I keep getting this problem with mysqli_result. It's a mysqli server. My error is: Fatal error: Cannot use object of type mysqli_result as array in /home/a7017672/public_html/login.html on line 34 My code is: <?PHP if(isset($_SESSION['loggedin'])) { die("You are already logged in!"); } if(isset($_POST['submit'])) { $email = mysqli_real_escape_string($con,$_POST['username']); $pass = mysqli_real_escape_string($con,$_POST['password']); $mysql = mysqli_query($con,"SELECT * FROM users WHERE email_address = '{$email}' AND password = '{$pass}'"); $mysql2 = mysqli_fetch_array($mysql); if (!$mysql ||mysqli_num_rows($mysql) < 1) { die("Incorrect password!"); } $_SESSION['loggedin'] = "YES"; $_SESSION['email'] = $email; $_SESSION['fname'] = $mysql['first_name']; $_SESSION['lname'] = $mysql['last_name']; $_SESSION['add1'] = $mysql['address_1']; $_SESSION['add2'] = $mysql['address_2']; $_SESSION['county'] = $mysql['county']; $_SESSION['postcode'] = $mysql['postcode']; $_SESSION['tel'] = $mysql['tel_no']; $_SESSION['mobile'] = $mysql['mobile_no']; $_SESSION['team'] = $mysql['team']; $_SESSION['ismanager'] = $mysql['is_manager']; $_SESSION['isadmin'] = $mysql['is_admin']; $_SESSION['sysadmin'] = $mysql['is_sysadmin']; die("You are now logged in!"); } echo "<form method='POST'> <p style='font-size: 14pt;'>Username (Email): <br><input type='text' name='username' maxlength='50' size='30'> <br /> <p style='font-size: 14pt;'>Password:<br><input type='text' name='password' maxlength='50' size='30'><br /> <input type='submit' name='submit' value='Login'> </form>"; ?> Any help is greatly appreciated!
  13. I have a site, up and running on the internet and want to run it locally. On my Mac I have Zend CE and can access my database with mysqli without a problem. The existing site uses Pear MDB2 to access the database. So, I installed MDB2 on my local machine and still couldn't access the database through the MDB2 code that works on the web server. I added an array to try to open the database connection on port number 10088 but that doesn't make any difference. I am new to Pear and MDB2. Any help appreciated. To illustrate the problem I have created code that just opens the database directly and then fails with MDB2. Since it works in the first case, the database, username, etc. are all working. <?php ini_set("display_errors", "1"); error_reporting(-1); ini_set('include_path', ini_get('include_path') . ':/home/davidann/php'.':/usr/local/zend/bin'); //Mysqli direct include_once('setUnamePass.php'); $link = mysqli_connect("localhost", DBUSER, DBPASS, DATABASE) or die("Unable to connect!"); echo 'Success using mysqli directly'; $result= mysqli_close($link); //MDB2 include_once('MDB2.php'); define('DB_DSN', 'mysqli://'.DBUSER.':'.DBPASS.'@localhost/'.DATABASE); class valuation { public function __construct() { //open database connection //$options = array( // 'port' => 10088,); $this->db_connection = MDB2::connect(DB_DSN); if (PEAR::isError($this->db_connection)) { exit($this->db_connection->getMessage()); } //set fetch mode to associative $this->db_connection->setFetchMode(MDB2_FETCHMODE_ASSOC); } } $valuation = new valuation(); ?> The output is as follows: Success using mysqli directly Strict Standards: Declaration of MDB2_Driver_Common::raiseError() should be compatible with that of PEAR::raiseError() in /usr/local/zend/bin/MDB2.php on line 990 Strict Standards: Non-static method MDB2::connect() should not be called statically, assuming $this from incompatible context in /usr/local/zend/apache2/htdocs/NewFolder/NewFolder/ezvaluation2/www/ezvaluation.com/valuation/testdbopen.php on line 22 Strict Standards: Non-static method MDB2::factory() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 433 Strict Standards: Non-static method MDB2::parseDSN() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 376 Strict Standards: Non-static method MDB2::loadClass() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 385 Strict Standards: Non-static method MDB2::classExists() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 327 Strict Standards: Non-static method MDB2::fileExists() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 335 Strict Standards: Non-static method MDB2::raiseError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 340 Strict Standards: Non-static method PEAR::raiseError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 574 Strict Standards: Non-static method MDB2::errorMessage() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 972 Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 743 Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 386 Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/bin/MDB2.php on line 434 Strict Standards: Non-static method PEAR::isError() should not be called statically, assuming $this from incompatible context in /usr/local/zend/apache2/htdocs/NewFolder/NewFolder/ezvaluation2/www/ezvaluation.com/valuation/testdbopen.php on line 23 MDB2 Error: not found
  14. Okay, here is the required information: Apache/2.2.22 (Ubuntu) MySQL client version: 5.5.34 PHP extension: mysqli Here are the three raw sql statements, using sample data. Statement 1: SELECT uuid FROM EmptyCart WHERE uuid = '52b6392b-c55f-71ef-2437-c0645d3d5ea0' Statement 2: UPDATE EmptyCart SET fname="so", lname="this", company="should", address="insert", city="", state="", zip="", phone="", country="US", cart_coupon="", email="", orderSubTotal="46.15", orderTotal="46.15", numOfItems="2", items="a:2:{i:0;s:5:item1;i:1;s:5:item2;}", ids="a:2:{i:0;s:3:id1;i:1;s:3:id2;}", codes="a:2:{i:0;s:5:code1;i:1;s:5:code2;}", qtys="a:2:{i:0;s:1:1;i:1;s:1:1;}", price="a:2:{i:0;s:5:44.95;i:1;s:3:1.2;}", orderTax="0", orderShipping="0", appliedPromoIdList="", coupon="", storeId="storeid", activeShipPromotionCount="", itemImages="a:2:{i:0;s:6:image1;i:1;s:6:image2;}", date="Mon Dec 02 2013 13:40:38 GMT-0500 (Eastern Standard Time)" WHERE uuid='52b6392b-c55f-71ef-2437-c0645d3d5ea0' Statement 3: INSERT INTO EmptyCart (uuid,fname,lname,company,address,city,state,zip,phone,country,cart_coupon,email,orderSubTotal,orderTotal,numOfItems,items,ids,codes,qtys,price,orderTax,orderShipping,appliedPromoIdList,coupon,storeId,activeShipPromotionCount,itemImages,date) VALUES ("52b6392b-c55f-71ef-2437-c0645d3d5ea0","so","this","should","insert","","","","","US","","","46.15","46.15","2","a:2:{i:0;s:5:item1;i:1;s:5:item2;}","a:2:{i:0;s:3:id1;i:1;s:3:id2;}","a:2:{i:0;s:5:code1;i:1;s:5:code2;}","a:2:{i:0;s:1:1;i:1;s:1:1;}","a:2:{i:0;s:5:44.95;i:1;s:3:1.2;}","0","0","","","storeid","","a:2:{i:0;s:6:image1;i:1;s:6:image2;}","Mon Dec 02 2013 13:40:38 GMT-0500 (Eastern Standard Time)") No errors are being returned, in fact, the queries all work fine. What is happening is actually within the PHP, however I have included the SQL statements as they may be causing the logic errors in the PHP code operation. Here is the section of PHP code where the error is happening: mysqli_select_db($con,$mysql_database); $prequery = mysqli_query($con,"SELECT uuid FROM ".$mysql_table." WHERE uuid = '".$tablevalues[0]."'"); $tango = $prequery->fetch_assoc(); if ($tango["uuid"]=$tablevalues[0]) { $new_count = count($tablefields); $mysql_update = ""; for ($z=1;$z<$new_count-1;$z++){ $mysql_update .= $tablefields[$z]."=".$tablevalues[$z].", "; } $mysql_update .= $tablefields[27]."=".$tablevalues[27]; $sql = "UPDATE ".$mysql_table." SET ".$mysql_update." WHERE uuid='".$tango["uuid"]."'"; } else { $sql = "INSERT INTO {$mysql_table} ({$tablefields_implode}) VALUES ({$tablevalues_implode})"; } // pprint_r($sql); mysqli_query($con,$sql); mysqli_close($con); The Correct Functionality should be: On the client-side, a new user visits the page the form resides on and begins filling out the form. Upon initial visit, a unique identifier is assigned to the user and stored in localstorage. Every time a form field is updated/changed the value is stored in localstorage. Every 30 seconds, selected contents of the form data (as pulled from localstorage) are sent to our server database via Ajax POST. The PHP Processing file receives the POST data and performs a series of SQL injection prevention functions on the data. The PHP file constructs a new array of cleaned data and uses that data array to construct the mysqli queries above. What should happen is the unique identifier should be checked against existing database entries and if it exists the relevant entry should be updated. If the unique identifier does not exist, a new entry is made. What is currently happening: Every incoming POST is evaluated and results in an UPDATE statement, even if the unique identifier does not exist in the database. Things I have tried: I have tried changing the value of the request for $prequery to reference a variable established earlier in the processing, but the result was the same. The code selects from the database and is still somehow evaluating that nothing = something. Notes: The first SQL statement, the select one, is the reason for the change of the variable to one earlier in the array processing. The value of the variable was being displayed with double quotes around it and breaking the SQL statement, however even with the new variable that does not have the double quotes the operation is still resulting in an Update instead of Insert despite the uuid not being in the database.
  15. How can i add total of user's following me? The code I currently have displays ALL the user's following me, instead of saying *numbers of user's following me* <?php $friends = Friends::getFriendsForUser($data->id); if (count($friends) > 0) { $db = DB::getInstance(); foreach($friends as $friend_id) { $friend = $db->query('SELECT name, username FROM users WHERE id = ?', array($friend_id)); if ($friend->count() == 1) { echo '<table> <tr> <td><img src="images/avatar.png"></td> <td><a href="profile.php?user='.escape($friend->first()->username).'">'.$friend->first()->name.'</a></td> </tr> </table>'; } } } else { echo 'Not following anyone.'; } ?>
  16. I'm learning how to use PHP and prepared statements with mysqli/php and can't seem to get this code to output data. I get no error messages, just nothing output. This is the complete code, it's rather simple, created from an example I found online. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Untitled</title> </head> <body> <?php require_once('/includes/conn.inc.php'); $conn = dbConnect('read'); $stmt = $conn->stmt_init(); // Create a prepared statement if($stmt->prepare("SELECT 'name' FROM comments WHERE 'approved' = ?")) { // Bind your variable to replace the ? $stmt->bind_param('s', $approved); // Set your variable $approved = "Y"; // Execute query $stmt->execute(); // Bind your result columns to variables $stmt->bind_result($name); // Fetch the result of the query while($stmt->fetch()) { echo $name . ' - ' . "found"; // John Doe - Unknown... } // Close statement object $stmt->close(); } ?> </body> </html>
  17. I'm not really sure what's going on, but I have been replacing all of my mysql queries with mysqli, and so far it is working fine, until I got to this one in particular... I am getting this error... "Warning: mysqli::prepare(): Couldn't fetch mysqli" and this error... "Warning: mysqli::close(): Couldn't fetch mysqli" I researched that problem, but none of what others had to say about fixing it, applied nor worked for me. What's funny about it is that just above that query, is another query in which has no problems... Here's the top query that works fine: $sql = "SELECT * FROM Agencies ORDER BY AgencyName ASC"; if ($result = $mysqli -> query($sql)) { while ($row = $result -> fetch_assoc()) { echo '<option value="'.$row['AgencyID'].'">'.$row['AgencyName'].'</option>'; } $result -> free(); } $mysqli -> close(); Now here's the query that is throwing the errors: $sql = "SELECT AgenciesAgents.*, Agents.AgentFirstName, Agents.AgentLastName FROM AgenciesAgents LEFT JOIN Agents ON AgenciesAgents.AgentID = Agents.AgentID WHERE AgenciesAgents.AgencyID = ? "; if ($stmt = $mysqli -> prepare($sql)) { $stmt->bind_param("i", $AgencyID); $stmt->execute(); while ($row = $stmt -> fetch_assoc()) { echo '<p><span style="vertical-align: top; color: #515151;">'.$row['AgentLastName'].', '.$row['AgentFirstName'].'</span><a href="agency-agent-correlations.php?function=deletecorrelation&agencyid='.$AgencyID.'&agentid='.$row['AgentID'].'" onclick="return confirm(\'Are you certain you wish do delete this agent?\');"> <img src="images/delete_icon.png" width="20" height="20" /></a></p>'; } $stmt -> free(); } $mysqli -> close();
  18. I am having an issue where the output from a MySQL stored procedure is not handled correctly, when there is NO resultset, as opposed to a NULL resultset. For example: 1) select * from myTable; //this works, there are 0,1, multiple records returned 2) select * from myTable where 1=2; //this works, there are 0 records returned in a NULL resultset 3) set user_level = 'user'; if user_level = 'admin' then select * from myTable; //this never hits end if; There is an error in #3, the query is never touched, so NO resultset is returned. This is different from what happens in example #2, where a resultset is returned, it is just NULL. My code looks like this: if ( ($result = $mysqli_conn->query($SQL)) == false ) { printf("Invalid query: %s\nWhole query: %s\n", $mysqli_conn->error, $SQL); } else { while ($myrow = $result->fetch_array(MYSQLI_ASSOC)) { ... do something here } Any thoughts on how to handle this cleanly? Thanks all, Frank
  19. I'm having issues converting to MySQLI, can someone take a look for me. Thanks, salestatusupdateplusone.php
  20. I'm trying to pass a NULL to a stored procedure in a PHP script to MySQL, and I am scrubbing the variables using mysql_real_escape_string, but the NULLs that are passed are giving me problems. My script should look like this: call spMyStoredProc(1,2,NULL,'username'); but unfortunately I get: call spMyStoredProc(1,2,,'username'); I am wondering if I want to move away from using mysql_real_escape_string, and possibly write my own function? Anybody have any ideas? thanks, Frank C
  21. So what i am trying to do is based on a administrative section of the website to edit pictures in a section of the website. the page displays all the images in the database, each image has 3 inputs to them, all based under one form for all pictures. so each picture has two checkboxes and one number input. First checkbox is based on if the picture will be active or not for displaying on the website. second input is the order of when this picture will be displayed ( yes this is for a feature banner that changes images based on time ). the last input is the second checkbox for deleting the photo(this checkbox is working fine as it uses a different submit button). I have this page set up so it will have all the active pictures already checked. now when trying to "uncheck" the active picture, it will not change the status of active. I will provide the code for the whole thing, maybe im going about this the wrong way. just mainly need some direction on how to go about what im trying to accomplish. my database layout: NAME: feature | id | position | pic | active | ======================== | 1 | 3 | jpg | true | | 2 | 1 | jpg | true | | 3 | NULL | jpg | false | | 4 | 2 | jpg | true | <form method="post" id="delete" name="delete"> <?php $pic_query = mysqli_query($con, "SELECT * FROM feature") or die("Pic_Query Failed: ".mysqli_error($con)); $count = mysqli_num_rows($pic_query); while($row = mysqli_fetch_array($pic_query)){ extract($row); if($active=='true'){ $checked = 'checked'; }else{ $checked = NULL; } ?> <div style="display:inline-block; margin: 4px; padding:5px; border:solid 1px #000000; border-radius:5px;"> <img src="../images/feature/<?php echo $pic ?>" width="200px"> <br>Active: <input type="checkbox" id="active[<?php echo $id ?>]" name="active[]" value="true" <?php echo $checked ?>> <br>Position: <input type="number" id="pos[<?php echo $id ?>]" name="pos[]" min="1" max="5" value="<?php echo $position; ?>"> <br>Delete: <input type="checkbox" id="checkbox[<?php echo $id; ?>]" name="checkbox[]" value="<?php echo $id; ?>"> </div> <?php } if(isset($_POST['delete'])){ for($i=0;$i<count($_POST['checkbox']);$i++){ $checkbox = $_POST['checkbox']; $del_id = $checkbox[$i]; $byebye = mysqli_query($con, "SELECT * FROM feature WHERE id='$del_id'") or die("File Delete Error: ".mysqli_error($con)); while($rows = mysqli_fetch_array($byebye)){ extract($rows); unlink("../images/features/".$pic); } $sql = "DELETE FROM pictures WHERE id='$del_id'"; $result = mysqli_query($con, $sql) or die("Delete Error: ".mysqli_error($con)); } // if successful redirect to delete_multiple.php if($result){ echo "<meta http-equiv=\"refresh\" content=\"0;URL=feature-pics.php\">"; } } mysqli_close(); if(isset($_POST['activate'])){ for($n=0;$n<count($_POST['active']);$n++){ $live = $_POST['active'][$n]; $pos = $_POST['pos'][$n]; $act_id = $active[$n]; $update = "UPDATE feature SET position='$pos', active='$live' WHERE id='$act_id'"; $result = mysqli_query($con, $update) or die("Active Error: ".mysqli_error($con)); echo "<br>".$live; //Testing whats being sent echo "<br>".$pos; //Testing whats being sent } // if successful redirect to delete_multiple.php if($result){ echo "" //meta refresh here, took out for testing } } mysqli_close(); ?> <br> <input type="submit" name="activate" id="activate" value="Activate"> <input type="submit" name="delete" id="delete" value="Delete Selected"> </form>
  22. Greetings all, So I'm starting to play around with incorporating databases into dynamic pages and I've come across an issue that was only vaguely covered during my PHP course in college. The script below works great except that it needs a natsort and I'm not sure how to do a natsort and still make the while loop work. I'm not even sure how to go about writing it. The script queries the database for the video names, video descriptions and then turns them into links (with a little css and java help). But after video 9 it starts to order incorrectly. It goes ...1, 10, 11, 12, 2, 3, 4, 5.... you get the idea, needs a natsort. I just don't have a clue how to go about doing that and keeping the while loop working. I tried a couple things but I'm just not figuring this out. <?php require ('masters/connect.php'); // Define the query: $q = "SELECT * FROM videofiles WHERE folder='" . $sect . "' ORDER BY vidname"; $r = @mysqli_query ($connect, $q); // Count the number of returned rows: $num = mysqli_num_rows($r); if ($num > 0) { // Table header: echo '<h1>Section Lessons</h1>'; echo '<table id="link-table">'; // Set up array to remove beginning url from database section names. $sectpattern = $sect; $patterns = array(); $patterns[0] = '/videos/'; $patterns[1] = '/\//'; $patterns[2] = '/' . $sectpattern . '/'; $patterns[3] = '/\\.[^.\\s]{3,4}$/'; $replacements = array(); $replacements[0] = 'Lesson '; // Fetch and print all the records: while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { echo '<tr> <td>' . "<a href=\"javascript:create_window('".$row['vidname']."',640,360)\">Click Here</a>" . '</td> <td align="left"> <div id="tabledataimage1"> <img src="'. $row['vidimage'] .'" width="100"/> </div> <div id="tabledatatitle1"> <h4>' . preg_replace($patterns, $replacements, $row['vidname']) . '</h4> </div> <div id="tabledatadesc1"> ' . $row['viddesc'] . ' </div> </td> </tr>'; } echo '</table>'; mysqli_free_result ($r); } else { // Inform that no entries were returned from the query. echo '<p>There are currently no videos in this section.</p>'; } // Close database connection: mysqli_close($connect); ?> As always any help is greatly appreciated. I'm having a lot of fun learning PHP but I still have a long ways to go. Best Regards, Nightasy
  23. Hey, guys, I'm new in the whole php thing. I believe what I am asking here is super simple to do, I just wasn't able to find it anywhere. In the code below, you guys will notice that not all the fields show in every change of the dropdown menu TYPE, and, of course they don't, that's the whole point. I mean, I have arranged for each TYPE to have it's own fields. The thing is: how can I adapt for the html ECHO code to show ONLY the "labels", I mean, the pieces of HTML in the while($row = mysqli_fetch_array($result)), for the fields that were filled in? I mean, I don't want that in RESULT there are the "labels" of the fields whose values are there. <?php $con=mysqli_connect("localhost","root","","activitytest1"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if (isset($_POST['submit'])) { $stmt = mysqli_prepare($con, "INSERT INTO activitytest1 (type, author, taskpre, taskdescription, outcome, semipre, semiwhile, exercisedescription, practicepre, practiceinstructions, leadin, gamepre, gameinstructions, videopre, videowhile, videopost, songpre, songwhile, songpost, mimioinstructions, otherinstructions, path, books, grouping, time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"); mysqli_stmt_bind_param($stmt, 'sssssssssssssssssssssssss', $type, $author, $taskpre, $taskdescription, $outcome, $semipre, $semiwhile, $exercisedescription, $practicepre, $practiceinstructions, $leadin, $gamepre, $gameinstructions, $videopre, $videowhile, $videopost, $songpre, $songwhile, $songpost, $mimioinstructions, $otherinstructions, $path, $books, $grouping, $time); $type = $_POST['type']; $author = $_POST['author']; $taskpre = $_POST['taskpre']; $taskdescription = $_POST['taskdescription']; $outcome = $_POST['outcome']; $semipre = $_POST['semipre']; $semiwhile = $_POST['semiwhile']; $exercisedescription = $_POST['exercisedescription']; $practicepre = $_POST['practicepre']; $practiceinstructions = $_POST['practiceinstructions']; $leadin = $_POST['leadin']; $gamepre = $_POST['gamepre']; $gameinstructions = $_POST['gameinstructions']; $videopre = $_POST['videopre']; $videowhile = $_POST['videowhile']; $videopost = $_POST['videopost']; $songpre = $_POST['songpre']; $songwhile = $_POST['songwhile']; $songpost = $_POST['songpost']; $mimioinstructions = $_POST['mimioinstructions']; $otherinstructions = $_POST['otherinstructions']; $path = $_POST['path']; $books = $_POST['books']; $grouping = $_POST['grouping']; $time = $_POST['time']; $submit = $_POST['submit']; mysqli_stmt_execute($stmt); mysqli_stmt_close($stmt); } $result = mysqli_query($con,"SELECT * FROM activitytest1"); while($row = mysqli_fetch_array($result)) { echo "<table width='909' border='1' align='center' cellpadding='5' cellspacing='0'> <tr> <th width='125' scope='col'>Type</th> <th width='680' scope='col'>Description</th> <th width='120' scope='col'>Author</th> </tr></table> <br/> <table width='909' border='1' align='center' cellpadding='5' cellspacing='0'> <tr> <td width='125'>" . $row['type'] . "</th> <td width='680'>Time:" . $row['time'] . " min. <br><br>" . $row['books'] . "<br/>Grouping: " . $row['grouping'] . "<br/>Preview the Task:" . $row['taskpre'] . "<br/>Instructions:" . $row['taskdescription'] . "<br/>Outcome:" . $row['outcome'] . "<br/>Preview the semi-task:" . $row['semipre'] . "<br/>Instructions:" . $row['semiwhile'] . "<br/>Exercise Instructions: " . $row['exercisedescription'] . "<br/> Preview the Practice:" . $row['practicepre'] . "<br/>Practice Instructions:" . $row['practiceinstructions'] . "<br/>Lead-in:" . $row['leadin'] . "<br/>Preview the Game:" . $row['gamepre'] . "<br/>Game Instructions:" . $row['gameinstructions'] . "<br/>Song PRE:" . $row['songpre'] . "<br/>Song WHILE:" . $row['songwhile'] . "<br/>Song POST:" . $row['songpost'] . "<br/>Video PRE:" . $row['videopre'] . "<br/>Video WHILE:" . $row['videowhile'] . "<br/>Video POST:" . $row['videopost'] . "<br/>Mimio Instructions:" . $row['mimioinstructions'] . "<br/>Instructions:" . $row['otherinstructions'] . "<br/><br>Link/Path" . $row['path'] . "<br/></th> <td width='120'>" . $row['author'] . "</th> </tr></table> <br/> <hr size='1'/>"; } mysqli_close($con); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Test 1</title> </head> <body> <br> <table width="909" border="1" align="center" cellpadding="5" cellspacing="0"> <tr> <th width="125" scope="col">Type</th> <th width="680" scope="col">Description</th> <th width="120" scope="col">Author</th> </tr></table> <br> <form action="index.php" method="POST"> <table width="909" border="1" align="center" cellpadding="5" cellspacing="0"> <td width="125"><label> </label> <select name="type" id="type" onChange="display(this,'Task','Semi-task','Practice','Exercise','Lead-in', 'Game', 'Video','Song','Mimio','Other');"> <option value="Unselected" selected="selected">Choose one:</option> <option value="Task">Task</option> <option value="Semi-task">Semi-task</option> <option value="Practice">Practice</option> <option value="Exercise">Exercise</option> <option value="Lead-in">Lead-in</option> <option value="Game">Game</option> <option value="Video">Video</option> <option value="Song">Song</option> <option value="Mimio">Mimio</option> <option value="Other">Other</option> </select></td> <td width="680"><div id="Task" style="display:none"> Task: <br /> Lead-in/Preview the task: <textarea name="taskpre" cols="70" rows="2"></textarea> <br /> Instructions: <textarea name="taskdescription" cols="70" rows="2"></textarea> <br /> Outcome: <textarea name="outcome" cols="70" rows="2"></textarea> <br /> </div> <div id="Semi-task" style="display:none">Semi-task:<br /> Lead-in/Preview the task: <textarea name="semipre" cols="70" rows="2"></textarea> <br /> Instructions: <textarea name="semiwhile" cols="70" rows="2"></textarea> <br /> </div> <div id="Exercise" style="display:none">Exercise:<br /> Instructions/Obs.: <textarea name="exercisedescription" cols="70" rows="2"></textarea> </div> <div id="Practice" style="display:none"> Practice:<br /> Lead-in/Preview the task: <textarea name="practicepre" cols="70" rows="2"></textarea> <br /> Instructions: <textarea name="practiceinstructions" cols="70" rows="2"></textarea> <br /> </div> <div id="Lead-in" style="display:none"> Lead-in:<br> <textarea name="leadin" cols="70" rows="2"></textarea><br> </div> <div id="Game" style="display:none"> Game:<br /> Lead-in: <textarea name="gamepre" cols="70" rows="2"></textarea> <br /> Instructions: <textarea name="gameinstructions" cols="70" rows="2"></textarea> </div> <div id="Video" style="display:none"> Video: <br /> Pre: <textarea name="videopre" cols="70" rows="2"></textarea> <br /> While: <textarea name="videowhile" cols="70" rows="2"></textarea> <br /> Post: <textarea name="videopost" cols="70" rows="2"></textarea> </div> <div id="Song" style="display:none"> Song: <br /> Pre: <textarea name="songpre" cols="70" rows="2"></textarea> <br /> While: <textarea name="songwhile" cols="70" rows="2"></textarea> <br /> Post: <textarea name="songpost" cols="70" rows="2"></textarea> </div> <div id="Mimio" style="display:none">Mimio:<br /> Instructions:<br> <textarea name="mimioinstructions" cols="70" rows="2"></textarea> </div> <div id="Other" style="display:none">Other:<br /> Instructions:<br> <textarea name="otherinstructions" cols="70" rows="2"></textarea><br /> </div> </td> <td width="120"><input name="author" type="text" size="12" maxlength="25" /></td> </tr> <tr> <td colspan="3"> <select name="books" id="Books"> <option value="books open" selected="selected">books open</option> <option value="books closed">books closed</option> </select> <br /> <select name="grouping"> <option value="individual" selected="selected">individual</option> <option value="pairs">pairs</option> <option value="trios">trios</option> <option value="groups of 3 to 4 students">groups of 3 to 4 students</option> <option value="groups of 5 students">groups of 5 students</option> <option value="divide the class into 2 groups">divide the class into 2 groups</option> <option value="divide the class into 3 groups">divide the class into 3 groups</option> <option value="divide the class into 4 groups">divide the class into 4 groups</option> </select> <br /> about <input name="time" type="text" id="Time" size="1" /> min </td> </tr> <tr> <td colspan="3">Link/Path: <input name="path" type="text" id="Path" size="40" /></td> </tr> <tr> <td colspan="3"><input type="submit" name="submit" value="Post!" /></td> </tr> </table> </form> </body> </html>
  24. Hello all, I am trying to make a determination about the best way to move forward with my database code for both personal projects and for the company I work for. For my own projects, I used to use mysql functions but have started to switch over to PDO. The company I work for is still using mysql functions and they are a bit wary about switching over to either mysqli or pdo, as they have a lot of code to go through and they don't want to make a bad decision. So I started working on a database class that would replicate all of the mysql functions they were used to (fetch_assoc, fetch_array, num_rows, etc) and decided to make it so that, via a config, you could use mysqli OR pdo and then, in each function, it would do it's best to get the expected result. This way, the code for the company would only ever have to do something like: $db->query($sql); if($db->num_rows() > 0) etc... But the more I read up on PDO (which I have been using in a more proceedural way), it seems like this is already a wrapper, so in effect I'm wrapping a wrapper. So, bottom line, what are others doing to future proff their database code? I like the idea of a class with generic function names, because if there is ever another style to use (mysqlii?) we can just write up the proper functions inside of the existing class and they'll work without a hitch. But is this something that pdo already delivers? I know it's good for dealing with multiple types of databases (mysql, mssql, oracle) but this company will only ever be working with mysql, so I don't have to go overboard with considerations for that. Thanks for any help/advice! JD
  25. so I have a query that I need to basically split in half to display in two section on the web page. I have a left side and a right side that will be filled with random selected images from the database. <body> <div class="leftbar"> 4 images here </div> <div class="maincontent"> main content of viewed page </div> <div class="rightbar"> next 4 images here </div> </body> is there a way this can be done? the query i would be using would look like this... except I need to spit the results in half to display in the two "leftbar" and "rightbar" sections $images = mysqli_query($con, "SELECT * FROM pictures ORDER BY RAND() LIMIT 8") or die("Image Query Failed: ".mysqli_error($con));
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.