Prepared SQLi & SELECT

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
User avatar
hypedupdawg
Forum Commoner
Posts: 74
Joined: Sat Apr 10, 2010 5:21 am

Prepared SQLi & SELECT

Post by hypedupdawg »

I've recently started moving over to the mysqli_query methods as opposed to the old mysql_query methods, and have hit a roadblock - using prepared statements. What I would like to do is do a simple SELECT query. Non-prepared, I would do this:

Code: Select all

$result = mysqli_query($con,"SELECT * FROM `".$page_table."` ORDER BY id DESC LIMIT ".$page_start." , ".$page_limit_no);
$results = mysqli_fetch_array($result));
However, I don't know how to get the results from a prepared statement - in any way! I know how to execute queries on the database, just not how to get the results! I have tried doing something along the lines of:

Code: Select all

$stmt = mysqli_stmt_init($con);
if(mysqli_stmt_prepare($stmt, "SELECT * FROM 'sqltrial' WHERE usr = ? AND pass = ?"))
	{
	mysqli_stmt_bind_param($stmt, 'ss', $usr, $pass);
	$usr = 'annexample';
	$pass = 'passw0rd';
	mysqli_stmt_execute($stmt));
	}
But then, I don't know how to get the results of this query! Any pointers, functions etc. would be a great help.

EDIT: I generally work in a procedural style, but am trying to learn OOP
Kurby
Forum Commoner
Posts: 63
Joined: Tue Feb 23, 2010 10:51 am

Re: Prepared SQLi & SELECT

Post by Kurby »

mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: Prepared SQLi & SELECT

Post by mikosiko »

quick example using OOP

Code: Select all

if ($stmt = $mysqli->prepare("SELECT field1,field2 FROM tablename")) { 
  $stmt->execute();
  $stmt->bind_result($field1, $field2);
  while ($stmt->fetch()) { 
    echo "$field1 : $field2\n";
  }
the key is the bind_result statement... you must bind every column that your query return.
Post Reply