Hi all,
I have some problems running prepared statements in a function. I’m getting some warnings which I’m not sure what they mean. Anyway here is my code.
include_once 'login.php';
function read()
{
$parameters = array();
$results = array();
$username = 'iTenzo';
$mysql = new mysqli($server,$user,$pass,$db) or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('SELECT firstname, lastname FROM users WHERE username=?') or die('Problem preparing query');
$stmt->execute();
$meta = $stmt->result_metadata();
while ( $field = $meta->fetch_field() ) {
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while ( $stmt->fetch() ) {
$x = array();
foreach( $row as $key => $val ) {
$x[$key] = $val;
}
$results[] = $x;
}
return $results;
}
$results = read();
Here are the warnings I’m getting:
Warning: mysqli::mysqli() [mysqli.mysqli]: [2002] No such file or directory (trying to connect via unix:///var/mysql/mysql.sock) in /Users/tenzo/Sites/prepare_function.php on line 11
Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2002): No such file or directory in /Users/tenzo/Sites/prepare_function.php on line 11
Warning: mysqli::prepare() [mysqli.prepare]: Couldn't fetch mysqli in /Users/tenzo/Sites/prepare_function.php on line 12
Problem preparing query
On my localhost system this creates 4 massive errors because I am running with error_reporting turned on - not on my live server you understand!
Whats more with xDebug installed those errors are bright orange and spill out even more information;
Notice: Undefined variable: server in C:\\var\\www\\html\\code\\shell\\xxx.php : eval()'d code on line 6
Call Stack
# Time Memory Function Location
1 0.9665 146488 {main}( ) ..\\index.php:0
2 0.9691 199264 eval( ''$server = \\'EEK\\'; function read() {
echo "
server: $server
user: $user
pass: $pass
db: $db
";}$results = read();
0.9691 199480 read( ) ..\\index.php(492) : eval()'d code:10
So the lesson is not really give your functions access to the variables it needs, but learn how to debug your own code for the sake of your own sanity and effectiveness.
The term you are looking for is variable scope , it is not complicated - have a read and you should be able to work it out, if not come back and ask here again.