Page 1 of 1

Prepared SQLi & SELECT

Posted: Thu Jun 17, 2010 5:13 pm
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

Re: Prepared SQLi & SELECT

Posted: Fri Jun 18, 2010 2:21 pm
by Kurby

Re: Prepared SQLi & SELECT

Posted: Fri Jun 18, 2010 6:58 pm
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.