Page 1 of 1

OO MySQLi help

Posted: Fri Jan 17, 2014 11:10 pm
by me!
I am trying to convert from some old MySQL functions to MySQLi

From what I can tell this should work but it is not... ?

Code: Select all

// db connection include is working, but not shown.

// Generate a customer list
$sql='SELECT type, first_name, last_name, city, id FROM customers WHERE type = ?';
$type = 'R';
 
/* Prepare statement */
$stmt = $db->prepare($sql);
if($stmt === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
 
/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('s',$type);
 
$stmt->bind_result($type, $first_name, $last_name, $city, $id);
while ($stmt->fetch()) {
    echo $last_name . ' ' . $first_name . ' - '. $city .'<br>';
    }

$db->close();

Re: OO MySQLi help

Posted: Fri Jan 17, 2014 11:48 pm
by requinix
You never actually executed the query.

Re: OO MySQLi help

Posted: Sat Jan 18, 2014 7:13 am
by Celauran
Also, if you're just getting started on this, do yourself a favour and use PDO instead of MySQLi. You'll thank me later.

Re: OO MySQLi help

Posted: Sat Jan 18, 2014 3:58 pm
by me!
Thank You!

I added

Code: Select all

 $stmt->execute();
and it now works :D
Not sure if it's placement is proper, but it is working.

In regards to PDO, I was going to change it all to that but I hit problems (me not knowing it) and was hoping MySQLi was more like the existing MySQL commands. However since working with it a little it looks like they are not all that different in the way you code things if I am going to use object orientated methods? I know the functions are different but that just requires using Google.


New code with the execute:

Code: Select all

// Generate a customer list
$sql='SELECT type, first_name, last_name, city, id FROM customers WHERE type = ?';
$type = 'R';
 
/* Prepare statement */
$stmt = $db->prepare($sql);
if($stmt === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
}
 
/* Bind parameters. TYpes: s = string, i = integer, d = double,  b = blob */
$stmt->bind_param('s',$type);

$stmt->bind_result($type, $first_name, $last_name, $city, $id);
$stmt->execute();
while ($stmt->fetch()) {
    echo $last_name . ' ' . $first_name . ' - '. $city .'<br>';
    }

$db->close();

Re: OO MySQLi help

Posted: Sat Jan 18, 2014 4:49 pm
by Celauran
Named placeholders and not having to bind results is going to save you a lot of hair pulling. PDO and MySQLi are otherwise quite similar, and the examples in the PDO book should be plenty to get you started.

Re: OO MySQLi help

Posted: Sat Jan 18, 2014 4:55 pm
by me!
Thank You