Posted By

Nettuts on 06/25/10


Tagged

sql php statements prepared


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

screamwork
iqwebdev
tutmeister
vagrantradio
dantreacy
shawntysco
barbietunnie
fomigo
qubestream


Prepared Statements: Read


 / Published in: PHP
 

  1. $mysql = new mysqli('localhost', 'root', 'root', 'databaseName') or die('There was a problem connecting to the database');
  2. $stmt = $mysql->prepare('SELECT id, title, content FROM tableName');
  3. $stmt->execute();
  4. $stmt->bind_result($id, $title, $content);
  5.  
  6.  
  7. while($row = $stmt->fetch()) : ?>
  8.  
  9. <h2> <?php echo $title; ?> </h2>
  10. <p> <?php echo $content; ?> </p>
  11.  
  12. <?php endwhile; ?>

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Nettuts on June 25, 2010

1) Create mysqli connection, and pass the host, username, password, and desired database. 2) Prepare your SQL query. Replace mine with whatever you need to select. 3) Execute the statement 4) Bind the results to variables. Make sure that you pass the same number of arguments to bind_result as you selected in your SQL query -- in this case, three. 7) Cycle through the rows, and echo out the title and content.

Posted By: aelien on June 26, 2010

Cool, and what if we need parameters in the statement? Can you give an example or a link to one? Thanks.

Posted By: Nettuts on June 26, 2010

@aelien - Sure, you use ? and then bind the parameters, accordingly. I'm heading out for the evening, but I'll add a new snippet tomorrow.

Posted By: sacha on January 7, 2011

@Nettuts - Could you past the snippet with parameters pls?

You need to login to post a comment.