Jump to content

Search the Community

Showing results for tags 'mysqli'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • 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

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. I have extensively searched the web for this but haven't found anything that can help! At the moment I have three loops: // loop 1 finds the answers if(isset($_POST['qanswer'])){ ($question = $_POST['qanswer']); for($i=0; $i < count($question); $i++) { echo "POSTED ANSWERS" . $question[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Answers POSTED!</p>'; } // loop 2 finds the comments if(isset($_POST['canswer'])){ ($comment = $_POST['canswer']); for($i=0; $i < count($comment); $i++) { echo "POSTED COMMENTS" . $comment[$i] . "<br/>"; } } else { echo '<p style="color: Red">No Comments POSTED!</p>'; } // loop 3 combines the answers and comments for($x = 0; $x < count($comment); $x++){ if(isset($question[$x])){ $question[$x] = $question[$x] . ' ' . $comment[$x]; } } $result = $question; // saves the answers and comments as a string ($result) Each comment[$i] is the same key and $question[$i]. Inserting into the table i have: $query = "INSERT INTO audit_data (Q4101, Q4102, Q4103, Q4104, etc...) VALUES '$result[0]','$result[1]','$result[2]','$result[3]','$result[4]', etc...)"; mysqli_query($link, $query) or die(mysqli_error($link)." Q=".$query); 1) is this the best way to go about this? 2) It is nearly working, i can get the $question and $comment into the first columns for instance: $result[0] to result[10] but if i try to insert further on in the table say $result[40] to $result[50] i only get the $question values and no $comment values. I have looked at array_map and preg_match on the manual but not sure how or which one to use. I don't want the table normalized and i am aware of injection problems.
  2. Hello, I´m trying to insert data from a form into a mysql table using mysqli and php. I use the code below to connect to the database: $host = "myhost"; $db = "a5066994_tutors"; $user = "a5066994_tutors"; $pass = "mypassword"; $connection = mysqli_connect("$host", "$user", "$pass", "$db"); if ($connection->errno) { printf("Connect failed: %s\n", $connection->error); exit(); and the code below to insert: $stmt = $connection->prepare("INSERT INTO tutorials (Author, Website, Title, Body1, Body2, Body3, Body4, Subtitle1, Subtitle2, Subtitle3, Subtitle4, Category, WTitle, Userid) VALUES ('$author','$website', '$title', '$text1', '$text2', '$text3', '$text4', '$s1', '$s2', '$s3', '$s4', '$cat', '$wtitle', '$userid') "); And it results in this error: Call to a member function execute() on a non-object I have also tried doing a var dump of the connection, which results in: object(mysqli)#1 (0) { } and a var dump of the statement, which results in: bool(false) Any help would be great, thank you!
  3. Having trouble submitting a dynamically generated form. I am getting no errors on submit, and nothing written to my table, just an indicator that I have landed on my "submit.php". The form is generated by checkboxes with action="../auditsys/submit.php" the checkbox form is echoed in php with variables as the values ie. $iso40 is the first form etc. which is reflected in the issets below. All the columns in "audit_data" table correspond to the $_POST values and subsequently to the input field "name " attribute. I can show the html form if requested, i haven't because it's long and embarrassingly messy at the moment. submit.php:<?php ini_set('display_errors',1); error_reporting(E_ALL); echo "landing at form indicator <br>"; $host = "localhost"; $username = "XXX"; $password = "XXX!"; $database = "XXX"; $link = mysqli_connect("$host", "$username", "$password", "$database"); if ($_SERVER['REQUEST_METHOD'] == 'POST') { if(isset($value, $iso40, $iso42, $iso50, $iso54, $iso55, $iso56, $iso60, $iso70, $iso73, $iso74, $iso75, $iso76, $iso80, $iso84, $iso85)) { $query = "INSERT INTO audit_data VALUES ('','{$_POST[auditor]}','{$_POST[auditee]}','{$_POST[datum]}','{$_POST[department]}','{$_POST[func]}','{$_POST[proc]}','{$_POST[audit_type]}', '{$_POST[copy_to]}','{$_POST[comments]}','{$_POST[Q4101]}','{$_POST[Q4102]}','{$_POST[Q4103]}','{$_POST[Q4104]}','{$_POST[Q4105]}','{$_POST[Q4106]}', '{$_POST[Q4107]}','{$_POST[Q4108]}','{$_POST[Q4109]}','{$_POST[Q4110]}','{$_POST[Q4211]}','{$_POST[Q4212]}','{$_POST[Q4213]}','{$_POST[Q4214]}', '{$_POST[Q4221]}','{$_POST[Q4222]}','{$_POST[Q4223]}','{$_POST[Q4231]}','{$_POST[Q4232]}','{$_POST[Q4233]}','{$_POST[Q4234]}','{$_POST[Q4235]}', '{$_POST[Q4236]}','{$_POST[Q4237]}','{$_POST[Q4238]}','{$_POST[Q4239]}','{$_POST[Q4241]}','{$_POST[Q4242]}','{$_POST[Q4243]}','{$_POST[Q4244]}', '{$_POST[Q4245]}','{$_POST[Q4246]}','{$_POST[Q4247]}','{$_POST[Q4248]}','{$_POST[Q5101]}','{$_POST[Q5102]}','{$_POST[Q5103]}','{$_POST[Q5104]}', '{$_POST[Q5105]}','{$_POST[Q5201]}','{$_POST[Q5301]}','{$_POST[Q5302]}','{$_POST[Q5303]}','{$_POST[Q5304]}','{$_POST[Q5411]}','{$_POST[Q5312]}', '{$_POST[Q5313]}','{$_POST[Q5421]}','{$_POST[Q5422]}','{$_POST[Q5423]}','{$_POST[Q5511]}','{$_POST[Q5521]}','{$_POST[Q5522]}','{$_POST[Q5523]}', '{$_POST[Q5531]}','{$_POST[Q5532]}','{$_POST[Q5611]}','{$_POST[Q5612]}','{$_POST[Q5613]}','{$_POST[Q5621]}','{$_POST[Q5622]}','{$_POST[Q5623]}', '{$_POST[Q5624]}','{$_POST[Q5625]}','{$_POST[Q5626]}','{$_POST[Q5627]}','{$_POST[Q5631]}','{$_POST[Q5632]}','{$_POST[Q5633]}','{$_POST[Q6101]}', '{$_POST[Q6102]}','{$_POST[Q6211]}','{$_POST[Q6221]}','{$_POST[Q6222]}','{$_POST[Q6223]}','{$_POST[Q6224]}','{$_POST[Q6225]}','{$_POST[Q6301]}', '{$_POST[Q6302]}','{$_POST[Q6303]}','{$_POST[Q6401]}','{$_POST[Q7101]}','{$_POST[Q7102]}','{$_POST[Q7103]}','{$_POST[Q7104]}','{$_POST[Q7105]}', '{$_POST[Q7106]}','{$_POST[Q7201]}','{$_POST[Q7202]}','{$_POST[Q7203]}','{$_POST[Q7204]}','{$_POST[Q7221]}','{$_POST[Q7222]}','{$_POST[Q7223]}', '{$_POST[Q7224]}','{$_POST[Q7225]}','{$_POST[Q7226]}','{$_POST[Q7231]}','{$_POST[Q7232]}','{$_POST[Q7233]}','{$_POST[Q7311]}','{$_POST[Q7312]}', '{$_POST[Q7313]}','{$_POST[Q7314]}','{$_POST[Q7315]}','{$_POST[Q7316]}','{$_POST[Q7321]}','{$_POST[Q7322]}','{$_POST[Q7323]}','{$_POST[Q7324]}', '{$_POST[Q7325]}','{$_POST[Q7326]}','{$_POST[Q7327]}','{$_POST[Q7331]}','{$_POST[Q7332]}','{$_POST[Q7333]}','{$_POST[Q7334]}','{$_POST[Q7335]}', '{$_POST[Q7336]}','{$_POST[Q7341]}','{$_POST[Q7342]}','{$_POST[Q7343]}','{$_POST[Q7344]}','{$_POST[Q7345]}','{$_POST[Q7351]}','{$_POST[Q7352]}', '{$_POST[Q7361]}','{$_POST[Q7362]}','{$_POST[Q7363]}','{$_POST[Q7364]}','{$_POST[Q7371]}','{$_POST[Q7372]}','{$_POST[Q7373]}','{$_POST[Q7374]}', '{$_POST[Q7411]}','{$_POST[Q7412]}','{$_POST[Q7413]}','{$_POST[Q7415]}','{$_POST[Q7421]}','{$_POST[Q7422]}','{$_POST[Q7423]}','{$_POST[Q7424]}', '{$_POST[Q7431]}','{$_POST[Q7432]}','{$_POST[Q7511]}','{$_POST[Q7512]}','{$_POST[Q7513]}','{$_POST[Q7514]}','{$_POST[Q7515]}','{$_POST[Q7516]}', '{$_POST[Q7521]}','{$_POST[Q7522]}','{$_POST[Q7523]}','{$_POST[Q7524]}','{$_POST[Q7525]}','{$_POST[Q7526]}','{$_POST[Q7527]}','{$_POST[Q7531]}', '{$_POST[Q7532]}','{$_POST[Q7533]}','{$_POST[Q7534]}','{$_POST[Q7541]}','{$_POST[Q7542]}','{$_POST[Q7543]}','{$_POST[Q7551]}','{$_POST[Q7552]}', '{$_POST[Q7553]}','{$_POST[Q7554]}','{$_POST[Q7555]}','{$_POST[Q7556]}','{$_POST[Q7557]}','{$_POST[Q7601]}','{$_POST[Q7602]}','{$_POST[Q7603]}', '{$_POST[Q7604]}','{$_POST[Q7605]}','{$_POST[Q7606]}','{$_POST[Q7607]}','{$_POST[Q7608]}','{$_POST[Q7609]}','{$_POST[Q7610]}','{$_POST[Q7611]}', '{$_POST[Q811]}','{$_POST[Q812]}','{$_POST[Q813]}','{$_POST[Q814]}','{$_POST[Q8211]}','{$_POST[Q8211]}','{$_POST[Q8211]}','{$_POST[Q8212]}', '{$_POST[Q8221]}','{$_POST[Q8222]}','{$_POST[Q8223]}','{$_POST[Q8224]}','{$_POST[Q8225]}','{$_POST[Q8226]}','{$_POST[Q8227]}','{$_POST[Q8228]}', '{$_POST[Q8229]}','{$_POST[Q8231]}','{$_POST[Q8232]}','{$_POST[Q8233]}','{$_POST[Q8241]}','{$_POST[Q8242]}','{$_POST[Q8243]}','{$_POST[Q8244]}', '{$_POST[Q8245]}','{$_POST[Q8401]}','{$_POST[Q8402]}','{$_POST[Q8403]}','{$_POST[Q8404]}','{$_POST[Q8405]}','{$_POST[Q8406]}','{$_POST[Q8511]}', '{$_POST[Q8512]}','{$_POST[Q8521]}','{$_POST[Q8522]}','{$_POST[Q8523]}','{$_POST[Q8524]}','{$_POST[Q8525]}','{$_POST[Q8526]}','{$_POST[Q8527]}', '{$_POST[Q8528]}','{$_POST[Q8531]}','{$_POST[Q8532]}','{$_POST[Q8533]}','{$_POST[Q8534]}','{$_POST[Q8535]}','{$_POST[Q8536]}','{$_POST[Q8537]}')"; echo $query; mysqli_query($link, $query) or die(mysqli_error($link)." Q=".$query); print_r($_POST); // ============ END ============== // } // if POST > END mysqli_close($link); } ?> I have checked and changed and checked my syntax but to no avail. Im using textpattern CMS if it's any use. I used the below to try and get an error code. Refs: PHP: Simple form to posts to database
  4. Hi php friends, I'll be very thankful to hear your opinion my php problem: I have a php website with mysql database with 1 table with about 20,000 rows. My code looks like this: $mysqli = new mysqli($mysql_hostname, $mysql_user, $mysql_password, $mysql_database); if ($mysqli->connect_errno) { exit(); } if ($stmt = $mysqli->prepare('SELECT title, description, content FROM '.$tableName.' WHERE slug=?')) { $stmt->bind_param("s", $slug); $stmt->execute(); $stmt->bind_result($title, $description, $content); $stmt->fetch(); $stmt->close(); } $mysqli->close(); ... /* just visualize the read variable above */ <h1><?php echo $title; ?></h1> <?php echo $content; ?> The problem is that in the hosting statistic, there's really huge php CPU usage, i.e. for yesterday the statistic is: PHP CPU usage is 144 min. MySQL CPU usage is 2 min. I try to find the problem for more than a week, I'll be very, very thankful for your help Thanks in advance for any reply!
  5. Hi All; I am trying to get some extensions to load in php 5.3.23. This was installed over 5.2.3 because 5.3 does not have an php5apache2_2.dll file. When I do a phpinfo mysql and mysqli do not show up. I have check the error logs and have seen the following, My OS is Win 7 64 bit. [22-Mar-2013 12:06:07] PHP Warning: PHP Startup: mysql: Unable to initialize module Module compiled with module API=20090626, debug=0, thread-safety=0 PHP compiled with module API=20060613, debug=0, thread-safety=1 These options need to match in Unknown on line 0 [22-Mar-2013 12:06:07] PHP Warning: PHP Startup: mysqli: Unable to initialize module Module compiled with module API=20090626, debug=0, thread-safety=0 PHP compiled with module API=20060613, debug=0, thread-safety=1 These options need to match in Unknown on line 0 Then in apache error.log file I noticed this: PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mcrypt.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mhash.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_mysqli.dll' - The specified module could not be found.\r\n in Unknown on line 0 PHP Warning: PHP Startup: Unable to load dynamic library 'C:\\PHP523\\ext\\php_pdo_mysql.dll' - The specified module could not be found.\r\n in Unknown on line 0 To me it looks like the double slashes might be the problem, but I don't know where to go to get rid of them, so am I on the right track, or is there something else wrong?
  6. I have the following code the lookup data from a database. It runs okay on my llocal machine but it give me "Fatal error: Allowed memory size of 33554432 bytes exhausted" whenit runs on hosting server. It indicates fatal error at line of $r[field3]); I googled the error and found the response for similar situation is to re-code to prevent memory leak. Can anyone point out how the following can be improve to prevent the error from happening. Thanks a lot. $stmt = $database_connection->stmt_init(); if ($stmt->prepare("SELECT keyA, field1, field2, field3 FROM tableA JOIN tableB ON tableA.field1 = tableB.keyB JOIN tableC ON tableA.field2 = tableC.keyC WHERE field3 LIKE ?")) { $stmt->bind_param('s', $likeString); $stmt->bind_result($r['keyA'], $r['field1'], $r['field2'], $r['field3']); if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; exit(); } while($stmt->fetch()){ foreach( $r as $key=>$value ) { $row_tmb[ $key ] = $value; } $r[] = $row_tmb; } return $r;
  7. Hi all. I'm pretty new to PHP and am trying to write a simple CMS using procedual PHP and MySQLi. Thought I'd build a CMS just to get a basic understanding of how things work. I know this would be better done with OOPHP and using PDO for databases interaction, however would appreciate any advice on how what I've done could be improved. The main areas I'm unsure on is..... Am I using mysqli_real_escape_string(); ok? When updating and deleteing users, is using the GET method ok as it seems a little unsafe when deleting users? Is the sanitization ok? Could I be making more use of functions, say for the session? If so how would you advise. Anything else that need improving? register.php - this is where I'm unsure on sanitization. Functions page is below this block of code. <?php require ('db-connection.php'); require ( 'functions.php' ); $pageTitle = 'Register'; if ( isset( $_POST['submitForm'] ) ) { $errors = array(); // puts errors into array if ( empty( $_POST['name']) ) { $errors['name'] = 'Please enter a name'; } else { $name = sanitize( $_POST['name'] ); $name = mysqli_real_escape_string( $dbc, $name ); } if ( empty ( $_POST['email'] ) ) { $errors['email'] = 'Please enter an email address'; } else { $email = sanitize( $_POST['email'] ); $email = mysqli_real_escape_string( $dbc, $email ); } if ( empty( $_POST['username']) ) { $errors['username'] = 'Please enter a username'; } else { $username = sanitize( $_POST['username'] ); $username = mysqli_real_escape_string( $dbc, $username ); } if ( empty( $_POST['password'] ) ) { $errors['password'] = 'Please enter a password'; } elseif ( $_POST['password'] !== $_POST['confirm_password'] ) { $errors['password'] = 'Passwords do not match'; } else { $salt = generateSalt( $_POST['username'] ); $password = generateHash( $salt, $_POST['password'] ); } $telephone = sanitize( $_POST['telephone'] ); $telephone = mysqli_real_escape_string( $dbc, $telephone ); $postcode = sanitize( $_POST['postcode'] ); $postcode = mysqli_real_escape_string( $dbc, $postcode ); if ( empty( $errors ) ) { $db_insert = "INSERT INTO users VALUES ( NULL, '$name', '$email', '$username', '$password', '$telephone', '$postcode' )"; mysqli_query( $dbc, $db_insert ); // performs query on db header( 'Location: login.php' ); } } require( 'header.php' ); ?> <h1>Register</h1> <form action="register.php" method="post" class="form-horizontal"> <?php if ( !empty ( $errors ) ) : ?> <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button> <p> <?php foreach ( $errors as $msg ) { echo $msg .'<br />'; } ?> </p> </div> <?php elseif ( empty( $errors ) && isset( $_POST['submitForm'] ) ) : ?> <p>Thank you for completing the form.</p> <?php endif; ?> <div class="control-group"> <label class="control-label" for="name">Name *</label> <div class="controls"> <input type="text" id="name" name="name" placeholder="Email" value="<?php echo isset($_POST['name']) ? $_POST['name'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="email">Email *</label> <div class="controls"> <input type="text" id="email" name="email" placeholder="Email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="username">Username *</label> <div class="controls"> <input type="text" id="username" name="username" placeholder="Username" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="username">Password *</label> <div class="controls"> <input type="password" id="password" name="password" placeholder="Password" value="<?php echo isset($_POST['password']) ? $_POST['password'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="confirm_password">Confirm Password *</label> <div class="controls"> <input type="password" id="cofirm_password" name="confirm_password" placeholder="Confirm Password" value="<?php echo isset($_POST['confirm_password']) ? $_POST['confirm_password'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="telephone">Telephone</label> <div class="controls"> <input type="text" id="telephone" name="telephone" placeholder="Telephone" value="<?php echo isset($_POST['telephone']) ? $_POST['telephone'] : ""; ?>"> </div> </div> <div class="control-group"> <label class="control-label" for="postcode">Postcode</label> <div class="controls"> <input type="text" id="postcode" name="postcode" placeholder="Postcode" value="<?php echo isset($_POST['postcode']) ? $_POST['postcode'] : ""; ?>"> </div> </div> <div class="control-group"> <div class="controls"> <button type="submit" class="btn btn-large btn-primary" name="submitForm">Register</button> </div> </div> </form> <?php require( 'footer.php' ); ?> functions.php <?php function generateSalt( $username ) { $salt = '$2a$10$'; $salt = $salt . md5(strtolower( $username )); return $salt; } function generateHash( $salt, $password ) { $hash = crypt( $password, $salt ); $hash = substr($hash, 29); return $hash; } function sanitize( $input ) { return htmlspecialchars(trim( $input )); } view-users.php - when displaying data from the database, do I need to run it through mysqli_real_escape_string(); before outputting to the user? How would that be done, just on the $result variable? Also with the delete user, I'm using the GET method, is this ok? This is opening the page which I've put the code below this block. <?php session_start(); if ( !isset( $_SESSION['username'] ) ) { header ( 'Location: login.php' ); } else { // set time-out period (in seconds) $inactive = 300; if (isset($_SESSION["timeout"])) { // calculate the session's "time to live" $sessionTTL = time() - $_SESSION["timeout"]; if ($sessionTTL > $inactive) { session_destroy(); header( 'Location: logout.php' ); } } $_SESSION["timeout"] = time(); } require( 'db-connection.php' ); require( 'functions.php' ); // $query = "SELECT * FROM users"; $query = "SELECT id, name, email, username, telephone, postcode FROM users"; $result = mysqli_query( $dbc, $query ); require( 'header.php' ); ?> <p><a href="logout.php">Logout</a></p> <table class="table table-striped"> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Username</th> <th>Telephone</th> <th>Postcode</th> <th>Edit User</th> </tr> <?php while ( $row = mysqli_fetch_array( $result, MYSQLI_ASSOC ) ) : ?> <?php $username = $row['username']; ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['username']; ?></td> <td><?php echo $row['telephone']; ?></td> <td><?php echo $row['postcode']; ?></td>> <td> <div class="btn-group"> <a class="btn" href="edit-user.php?username=<?php echo $username; ?>"><i class="icon icon-edit"></i></a> <a class="btn" href="delete-user.php?username=<?php echo $username; ?>"><i class="icon icon-trash"></i></a> </div> </td> </tr> <?php endwhile; ?> </table> <p><?php printf("Select returned %d rows.\n", mysqli_num_rows($result)); ?></p> <?php require( 'footer.php' ); ?> delete-user.php <?php session_start(); if ( !isset( $_SESSION['username'] ) ) { header ( 'Location: login.php' ); } require( 'db-connection.php' ); require( 'functions.php' ); if ( isset( $_GET['username'] ) ) { $username = $_GET['username']; $query = "DELETE FROM users WHERE username = '$username'"; $result = mysqli_query( $dbc, $query ); header( 'Location: view-users.php' ); } mysql_close( $dbc ); Thanks in advance.
  8. How does one go about converting an SQL query such as: SELECT * FROM members WHERE userid='$userid' AND code=$code' into a prepared statement for PHP. I understand how to use prepared statements however I'm having trouble with the * part of the query and I'd rather not have to write out all the table coulmns because I have about 20. EDIT: I'm using mysqli procedural
  9. HI, I am building a PHP and Mysqli based shopping cart for my UNI project. I have been using prepared statements for everything so far and they work great. However I have hit my first problem. I cannot seem to insert data into the database using a prepared statement. I have written a function that first checks to see if a product already exists. this works well and if that product does not exist it should run the prepared stmt and insert the data. However it is skipping over the insert part and going straight to the 'else' section of the 'if' stating that a product could not be uploaded. Here is the function that is not working. As before the first part works well, just have a problem when it actually comes to add the product. function addProduct($productName, $productPrice, $productCategory, $productShortDesc, $productLongDesc, $productShipping, $productQTY) { //Check if item already exists $qry = "Select id FROM products WHERE name = ? LIMIT 1"; if ($stmt = $this->conn->prepare($qry)) { $stmt->bind_param('s', $productName); $stmt->execute(); $stmt->bind_result($p_id); if($stmt->fetch()) { echo "Sorry. That product already exists."; exit(); } else { $qry2 = ("INSERT INTO products (name, short_desc, long_desc, category, price, shipping, qty) VALUES('$productName', '$productShortDesc', '$productLongDesc', '$productCategory', '$productPrice','$productShipping', '$productQTY'"); if ($stmt = $this->conn->prepare($qry2)) { //Add item to DB $stmt->execute(); $stmt->insert_id; //Place image in folder $newname = "$pid.jpg"; move_uploaded_file($FILES['fileField']['tmp_name'], "../product_images/$newname"); } else { echo "Error adding new product, Please check all details and try again."; } } } } Regards Chris
  10. I have the following to update database but somehow it is doing so. Anyone has an idea? I added break point inside this function to check the parms passed in and they are correct. function edit_book($book_id, $book_title) { $conn = mysqli_connect('localhost', 'user', 'pwd', 'db') or die('Could Not Connect' . mysql_error()); $book_id = (int)$book_id; $book_title = $conn->real_escape_string($book_title); $stmt = $conn->stmt_init(); //***************** Break point - examine the value of book_id and book_title if ($stmt->prepare("UPDATE book SET book_title=? WHERE book_id=?")) { $stmt->bind_param('si', $parm_book_id, $parm_book_title); $parm_book_id = $book_id; $parm_book_title = $book_title; $stmt->execute(); $stmt->close(); } mysqli_close($conn); }
  11. I have problem to fetch data into an array. The following code was original written in mysql and I need to convert it to use mysqli. Question 1: Do I need to have $stmt->bind_result ? Question 2: How do I convert from mysqli_fetch_assoc to mysqli_ ? Thanks for any help. if ($func_num_args > 1) { unset($func_get_args[0]); $fields = implode (', ', $func_get_args) ; $stmt = $database_connection->stmt_init(); if ($stmt->prepare("SELECT $fields FROM category WHERE book_id=?")) { $stmt->bind_param('i', $parm_book_id); $parm_book_idt = $book_id; $stmt->execute(); } // the following needs to be changed to use mysqli $data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM user WHERE id_user = $id_user")); return $data; }
  12. my code doesnt seem to work.. the radio buttons appear but nothing beside them .. what i know already: mysql_fetch_row is working - i have tested this using mysqli_num_rows() mysqli_query is working - testing in phpmyadmin and also proven above the problem seems to be with $a ..... $e .. i have tried to echo these variables outside teh form but they dont work. i have also tried to echo them directly ie. $retrieve['question']; and this doesnt work either. could someone please advise what is wrong? cheers ps. i am new at this. this is my code. <?php include 'dbyear2.php'; $qnumber = ($_REQUEST['uqn']); // obtain question number from URL $find = mysqli_query($condbyear2, "SELECT * FROM Renal WHERE UQN='$qnumber'"); while($retrieve=mysqli_fetch_row($find)); { $question = $retrieve['question']; $a = $retrieve['MCQ_A']; $b = $retrieve['MCQ_B']; $c = $retrieve['MCQ_C']; $d = $retrieve['MCQ_D']; $e = $retrieve['MCQ_E']; $answer = $retrieve['answer']; $correct = $retrieve['MCQ_correct']; } ?> <form action='check.php' method='POST'> <table> <tr><td></td><td></td></tr> <tr></tr> <tr><td><input type='radio' name='group1' value='A' /></td><td> <?php echo $a; ?></td></tr> <tr><td><input type='radio' name='group1' value='B' /></td><td> <?php echo $b; ?></td></tr> <tr><td><input type='radio' name='group1' value='C' /></td><td> <?php echo $c; ?></td></tr> <tr><td><input type='radio' name='group1' value='D' /></td><td> <?php echo $d; ?></td></tr> <tr><td><input type='radio' name='group1' value='E' /></td><td> <?php echo $e; ?></td></tr> <tr> <?php // sending the retrieved information from MYSQL via POST for use in check.php file $qnumber; $a; $b; $c; $d; $e; $answer; $correct; ?></tr> <tr><td><input type="submit" value="Submit"></td></tr> </table> </form>
  13. Hi all, I have a most strange problem, and I am not sure if it is because of a long overdue move to mysqli from mysql or something else that is ludicrously simply wrong with what I am doing. I am doing a select on name from users where the userid = the sessions userid. From there I want to set the $personsname variable from the name column - simple. The query below runs fine without error and I can print out the name, but what I cannot do is set the variable up: $query1 = "SELECT name FROM `users` WHERE `userid`=$userid"; $result = $mysqli->query($query1) or die($mysqli->error.__LINE__); // GOING THROUGH THE DATA if($result->num_rows > 0) { while($row = $result->fetch_assoc()) { echo stripslashes($row['name']); $personsname=stripslashes ($row['$name']); = FRED BLOGS - correct echo "<p>name=$personsname</p>"; = EMPTY?!?!?!?! I am sure the answer is embarrassingly simple, but I just cant get my head around this.. Thanks, G
  14. Hello, I want to switch from mysql to mysqli. but i have some questions. Are there an advantage to use object oriented style:$mysqli=new mysqli(...) or procedural style : $link=mysqli_connect(.....) ? My actual website, use mysql and all are procedural style : mysql_connect, mysql_query, mysql_num_rows.......... after doing a query, i close the connection mysql_close($link)... and reopen it if i have another query, such as in a function or further in the same script.... so it means that i can open and close the connection a lot in a same script...... I read that i can create an object like ::$mysqli=new mysqli(...) and nerver close it, and if i call a function, i just send $mysqli to the function: callThisFunction($mysqli) and the connection will be automaticly close when the script finish Is that better to open,close,open,close........ and so??? or open once and never close it I want to use the best way for the persomance of entire website! Thanks for your help!!
  15. My question is in the title, does anyone know any good tutorials to upload images to the server and send the path to the database. I did post a question about a piece of my code where you can upload images to the server but it wasn't associated with the database. I would love to hear back about this.
  16. I have been working on an application for a university project and I have somehow managed to break my code and I have no idea what I have done to break it. I have created a registration and log in script which used to work but I can no longer login with the registered details. I could really use some help on this so I don't spend hours ripping my hair out. I have attached an image of my user database. Code for registration <?php include 'PasswordHash.php'; $sql = new mysqli('localhost', '****', '****', '****'); // Create an array to catch any errors in the registration form. $errors = array(); /** * Make sure the form has been submitted before trying to process it. This is * single most common cause of 'undefined index' notices. */ if (!empty($_POST)) { // First check that required fields have been filled in. if (empty($_POST['username'])) { $errors['username'] = "Username cannot be empty."; } // Restrict usernames to alphanumeric plus space, dot, dash, and underscore. /* if (preg_match('/[^a-zA-Z0-9 .-_]/', $_POST['username'])) { $errors['username'] = "Username contains illegal characters."; } */ if (empty($_POST['firstname'])) { $errors['firstname'] = "First Name cannot be empty."; } if (empty($_POST['surname'])) { $errors['surname'] = "Surname cannot be empty."; } if (empty($_POST['password'])) { $errors['password'] = "Password cannot be empty."; } if (strlen($_POST['password']) < { $errors['password'] = "Password must be at least 8 charcaters."; } // Force passwords to contain at least one number and one special character. /* if (!preg_match('/[0-9]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one number."; } if (!preg_match('/[\W]/', $_POST['password'])) { $errors['password'] = "Password must contain at least one special character."; } */ if (empty($_POST['password_confirm'])) { $errors['password_confirm'] = "Please confirm password."; } if ($_POST['password'] != $_POST['password_confirm']) { $errors['password'] = "Passwords do not match."; } $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL); if (!$email) { $errors['email'] = "Not a valid email address."; } /** * Escape the data we're going to use in our query. Never trust user input. */ $username = $sql->real_escape_string($_POST['username']); $email = $sql->real_escape_string($email); $firstname = $sql->real_escape_string($_POST['firstname']); $surname = $sql->real_escape_string($_POST['surname']); $addressline1 = $sql->real_escape_string($_POST['addressline1']); $addressline2 = $sql->real_escape_string($_POST['addressline2']); $city = $sql->real_escape_string($_POST['city']); $county = $sql->real_escape_string($_POST['county']); $postcode = $sql->real_escape_string($_POST['postcode']); /** * Check that the username and email aren't already in our database. * * Note also the absence of SELECT * */ $query = "SELECT username, email FROM users WHERE username = '{$username}' OR email = '{$email}'"; $result = $sql->query($query); /** * There may well be more than one point of failure, but all we really need * is the first one. */ $existing = $result->fetch_object(); if ($existing) { if ($existing->username == $_POST['username']) { $errors['username'] = "That username is already in use."; } if ($existing->email == $email) { $errors['email'] = "That email address is already in use."; } } } if (!empty($_POST) && empty($errors)) { /** * Hash password before storing in database */ $hasher = new PasswordHash(8, FALSE); $password = $hasher->HashPassword($_POST['password']); $query = "INSERT INTO users (firstname, surname, username, email, password, addressline1, addressline2, city, county, postcode, created) VALUES ('{$firstname}','{$surname}','{$username}','{$email}', '{$password}','{$addressline1}','{$addressline2}','{$city}','{$county}','{$postcode}', NOW())"; $success = $sql->query($query); if ($success) { $message = "Account created."; } else { $errors['registration'] = "Account could not be created. Please try again later."; } } ?> Login Code <?php session_start(); // If the user is already logged in then redirect them to homepage if (isset($_SESSION['user_id'])) { exit(); } include 'PasswordHash.php'; $sql = new mysqli('localhost', '****', '****', '****'); $hasher = new PasswordHash(8, FALSE); if (!empty($_POST)) { // Again, never trust user input! $user = $sql->real_escape_string($_POST['username']); $query = "SELECT id, password, username, UNIX_TIMESTAMP(created) AS salt FROM users WHERE username = '{$username}'"; $user = $sql->query($query)->fetch_object(); /** * Check that the query returned a result (otherwise user doesn't exist) * and that provided password is correct. */ if ($user && $user->password == $hasher->CheckPassword($_POST['password'], $user->password)) { /** * Set cookies here if/as needed. * Set session data as needed. DO NOT store user's password in * cookies or sessions! * Redirect the user if/as required. */ session_regenerate_id(); $_SESSION['user_id'] = $user->id; $_SESSION['username'] = $user->username; $_SESSION['authenticated'] = TRUE; $_SESSION['signature'] = md5($user->id . $_SERVER['HTTP_USER_AGENT'] . $user->salt); header('Location:../login.php'); } /** * Don't provide specific details as to whether username or password was * incorrect. If an attacker knows they've found a valid username, you've * just made their life easier. */ else { $error = "Login failed."; } } ?> Thank you in advance and I'm sorry for the amount of code. Some of the code I used was from tutorials, as I am new to php.
  17. I am still really new to php so I am sorry if I don't make much sense but what I want to be able to achieve is to retrieve images from a file directory that will be referenced in the database. Here is my code for submitting the images <?php $allowedExts = array("jpg", "jpeg", "gif", "png"); $extension = end(explode(".", $_FILES["file"]["name"])); if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 20000) && in_array($extension, $allowedExts)) { if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br>"; } else { echo "Upload: " . $_FILES["file"]["name"] . "<br>"; echo "Type: " . $_FILES["file"]["type"] . "<br>"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>"; if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; } } } else { echo "Invalid file"; } ?> Here is my sql for the created table CREATE TABLE `recipes` ( `recipeid` INT(11) UNSIGNED ZEROFILL PRIMARY KEY AUTO_INCREMENT, `recipename` VARCHAR(50) NOT NULL, `ingredients` VARCHAR(50) NOT NULL, `instructions` VARCHAR(50) NOT NULL, `imagename` VARCHAR(50) NOT NULL, `created` DATETIME NOT NULL ) Thank you in advance.
  18. I'm using PHP 5.3.13. I am just using a very simple query to grab one column of results from a table. I would like to fetch them and then iteratively add them to a dropdown menu. I am trying to understand these methods/functions and seem to be missing something. My research on Google didn't give me any indication of what I'm doing wrong. I start with one of the simplest queries possible, which I know will return a data set as I have tested it in mysqladmin. The problem arises when I try to call the method on the mysqli_result object. $query = "SELECT `artist` FROM `bands`;"; $result = $mysqli->query($query); $bandArr = $result->fetch_all(); The error I'm getting from the above code is: Fatal error: "Call to undefined method mysqli_result::fetch_all()..." I researched this error and read somewhere that you need mysqlnd. Is that true? Do I need to look into my PHP configuration to get this to work? Is it worth it for this task? Then I tried fetch_array... $query = "SELECT `artist` FROM `bands`;"; $result = $mysqli->query($query); $bandArr = $result->fetch_array(MYSQLI_NUM); printf("%s\n%s", $bandArr[0], $bandArr[1]); And the above code for some reason returns an array with only one item, and this error: "Notice: Undefined offset: 1 in..." What am I missing here? Again, all I want is a small result set from one column which can be iterated and each value added to a drop down menu. Thoughts? Suggestions? Thanks in advance for any help you can offer...
  19. I would like to run a simple query one time without user input. Can I just use a query? Or is there benefit to doing it another way?
  20. I have a cart function that is supposed to use the post array (with product numbers as indices and the associated value is the customer's requested quantity) and populate product information in the session by accessing the database. I would like this function to add a $key and $value pair to $prodDetail for each item in the post array. Instead, it is replacing all the $value entries with the most recently selected product data. I do not see why it is resetting all of the $value fields upon each new iteration. Please let me know if this is still unclear after you have read the following. Here is the function that I believe is the culprit: function prodArr() { if (!empty($_POST['cart'])) { global $dbType; $prodDetail = Array(); //connect to database $mysqli = Database::getInstance(); //Retrieve product data if ($dbType === 'distro') { $results = array('img' => &$img, 'artist' => &$artist, 'title' => &$title, 'label' => &$label, 'year' => &$year, 'price' => &$price, 'qty' => &$qty); $tbl = 'products'; } elseif ($dbType === 'releases') { $results = array('img' => &$img, 'artist' => &$artist, 'title' => &$title, 'year' => &$year, 'price' => &$price, 'qty' => &$qty); $tbl = 'products'; } elseif ($dbType === 'merch') { $results = array('img' => &$img, 'title' => &$title,'size' => &$size, 'color' => &$color, 'sex' => &$sex, 'price' => &$price, 'qty' => &$qty); $tbl = 'merch'; } $query = 'SELECT '; $query .= '`'.implode('`, `', array_keys($results)).'`'; $query .= ' FROM ' . $tbl . ' WHERE (`id` = ?) AND (`qty` > 0) AND (`agedOff` <> 1);'; foreach ($_POST['cart'] as $elKey => $element) { if (!$stmt = $mysqli->prepare($query)) { echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; } if (!$stmt->bind_param('s', $elKey)) { echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error; } if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; } if (!call_user_func_array(array($stmt, 'bind_result'), $results)) { echo "Binding results failed: (" . $stmt->errno . ") " . $stmt->error; } if (!$stmt->fetch()){ echo "Fetching results failed: (" . $stmt->errno . ") " . $stmt->error; } $prodDetail[$elKey] = $results; printArray($prodDetail); I do not show the entire function, because I believe this is where the problem lies. Through dumping and echoing variables, I show that the $results array changes through each iteration of the foreach loop, but unfortunately it is setting all of the child arrays in $prodDetail to match the current $results array. All I want to do is add each new result set to the array. Maybe I have been staring at this for too long, but I can't seem to see the problem. Can someone please point how to fix this?
  21. I been trying to figure this out for about 3 or so hours (usually I wait 3 days of trying to fix something before I post here, but I can't wait xP) . . . and I am sure - as always - someone sees a simple fix and saves the day on PHPfreaks. Below is the code and details of what is happening is below. $stmt = $mysqli->prepare("SELECT question, uniqueid FROM pollquestion WHERE status = 1"); $stmt->execute(); $stmt->bind_result($question, $uniqueid); while ($stmt->fetch()) { echo "<center><div class=tablebox><h5>$question</h5></div></center><br><div class=tablebox>"; if (!$mysqli->query("SELECT optionname FROM pollchoices WHERE pollid = $uniqueid")) {echo "Multi-INSERT failed: (" . $mysqli->errno . ") " . $mysqli->error;} else{ $stmt2 = $mysqli->prepare("SELECT optionname FROM pollchoices WHERE pollid = ?"); $stmt2->bind_param('s', $uniqueid); mysqli_free_result(); $stmt2->execute(); $stmt2->bind_result($option); while ($stmt2->fetch()){echo "$option";} $stmt2->close(); } echo "</div>"; } $stmt->close(); With this I get the error "Multi-INSERT failed: (2014) Commands out of sync; you can't run this command now." I looked it up on Google and it was saying I should use multi_query. I replaced the query with multi_query and still no luck and no change in error. So I changed it back. I do stuff like this a lot in my coding and never came across this error. Should I be using multi_query? I never used it before, if so - how should I be using it? This is what I am trying to get to happen: I get the question for the poll and the unique id. With the unique id I can find out what poll options goes with it. That is all I want to do and I cannot get the poll options to show.
  22. Hello — This is probably one of the most common mysqli errors out there, but it has appeared on my webpage. The problem is on line 10. This file is used as a global functions file - so I can essentially use db_query(INSERT INTO...) in a different page and have the function run. For security reasons I have removed the actual usernames and such from the code, and it is pasted below. Any help would be greatly appreciated. <?php // Function to connect to the database. function db_connect() { $dbc = mysqli_connect('host','user','********','db'); } // Function to run database queries. function db_query($q) { global $dbc; $dbq = mysqli_query($dbc, $q); // ERROR OCCURS HERE if(!$dbq) { return false; } else { $r = mysqli_store_result($link); } } ?>
  23. Here is my mysqli query: SELECT `artwork`,`artist`,`title`,`label`,`year`,`price`,`id` FROM `products` WHERE (`qty` <> 0) AND (`agedOff` <> 1); I know this query works. I typed it into the mysqladmin window and it returned the desired results. Here is the variable setup & database query: $artwork = ''; $artist = ''; $title = ''; $label = ''; $year = 0; $price = 0.00; $id = ''; $vars = array(&$artwork, &$artist, &$title, &$label, &$year, &$price, &$id); //I placed the ampersands before the array values, because bind_results requires that you pass as reference if (!$stmt = $mysqli->prepare($query)) { echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error; } if (!$stmt->execute()) { echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error; } if (!call_user_func_array(array($stmt, 'bind_result'), $vars)) { echo "Binding results failed: (" . $stmt->errno . "( " . $stmt->error; } if($stmt->fetch) { //this part does not execute } The error message I receive is: "Notice: Undefined property: mysqli_stmt::$fetch in /hermes/waloraweb073/b2264/moo.katc/cobra/lib/distro.php on line 75 Fetching results failed: (0)" Can someone point me in the right direction please?
  24. I have multiple scripts referring to one another and it is getting a little confusing with database calls. I stumbled upon the singleton method, and I am trying to use it to create a Database class that will make sure there is only one connection at a time. This is what I have: class Database{ //Store the single instance of Database private static $m_pInstance; private function __construct(){ $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } } public static function getInstance() { if(!self::$m_pInstance) { self::$m_pInstance = new Database(); } return self::$m_pInstance; } } My connection definitions are stored in a cfg.php file which is required by this script. For the most part I understand how this works, but not well enough to understand why it isn't working. Here is the reference to this database: $mysqli = Database::getInstance(); Can someone help me figure out what I am doing wrong? The connection fails when I run it. It works when I put the above reference into a comment and simply connect with this: $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db); if ($mysqli->connect_error) { die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); } Thanks.
  25. Hello. Are there any GOOD tutorials about MYSQLI Object orientated coding, and procedural. IE - ONE PAGE that has procedural instructions and DOESNT EVEN BREATHE a sign of object-orientated, and the swapped version. I prefer Procedural. I've found tutorials that have both codes in one page - very confusing.. You use 1 line of procedural, and another line of object orientated & of course its causes errors. I want seperate pages/information. I've been coding for years and now want a new thing added to my site. So I COPY the exact WORKING code i have on a separate script to this new script, and now that same code doesn't work. my current code is here:- $link = mysqli_connect('SITE.com', 'blah', 'Blahpasswrd', 'moreblah'); if ($link->connect_errno) { $GLOBALS["jobs"].="Failed to connect to MySQL: " . $link=>connect_error; save_logs("XXXXXXXXXV06_JOBSCHECK",$GLOBALS["jobs"]); exit(); } $sql = "SELECT * FROM `jobs` WHERE `ID` LIKE '$job%';"; $GLOBALS["jobs"].="\n$sql\n\n";$result = $link->query($sql); $result = $link->query($sql); while($row = mysqli_fetch_assoc($result)) { $text.=print_r($row,true)."\n"; } the error message im getting is:- [10-Jun-2023 23:30:43 Pacific/Auckland] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in PATH.php on line 72 [10-Jun-2023 23:35:03 Pacific/Auckland] PHP Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, bool given in PATH.php on line 72 all i want is a list of each line/row of the database that matches.
×
×
  • 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.