PHP 8.5.0 Alpha 4 available for testing

Voting

: six plus one?
(Example: nine)

The Note You're Voting On

HeadlessDev
6 years ago
Thanks to everyone that leaves notes, without them I would not be able to do what I do. I wrote this function with help from notes on this page and others.

I did not have mysqlnd available to me, but wanted to be able to get_result() of a query as an object.

PLEASE NOTE: I am not an expert at PHP

Heres an example of using my get_result() to login users
<?php
//Sanitize input before using this function
function login($email, $password){
require
'connect_db.php';
$query = $sql->stmt_init();
if(
$query->prepare("SELECT CustomerId, Password, Admin FROM users WHERE Email = ?")){
$query->bind_param("s",$email);
$result = get_result($query); //USING FUNCTION HERE
if($result != NULL){
$user = $result[0];
if(
password_verify($password, $user->Password)){
$_SESSION['user_id'] = $user->CustomerId;
if(
$user->Admin == 1){
$_SESSION['admin'] = true;
}
$sql->close();
return
true;
}
}
}
$sql->close();
//If we get here they are not logged in
return false;
}

//Returns an array with each row as an object
function get_result($stmt){
$stmt->execute(); //Execute query
$stmt->store_result(); //Store the results
$num_rows = $stmt->num_rows; //Get the number of results
$results = NULL;
if(
$num_rows > 0){
//Get metadata about the results
$meta = $stmt->result_metadata();
//Here we get all the column/field names and create the binding code
$bind_code = "return mysqli_stmt_bind_result(\$stmt, ";
while(
$_field = $meta->fetch_field()){
$bind_code .= "\$row[\"".$_field->name."\"], ";
}
//Replace trailing ", " with ");"
$bind_code = substr_replace($bind_code,");", -2);
//Run the code, if it doesn't work return NULL
if(!eval($bind_code)) {
$stmt->close();
return
NULL;
}
//This is where we create the object and add it to our final result array
for($i=0;$i<$num_rows;$i++){
//Gets the row by index
$stmt->data_seek($i);
//Update bound variables used in $bind_code with new row values
$stmt->fetch();
foreach(
$row as $key=>$value){
//Create array using the column/field name as the index
$_result[$key] = $value;
}
//Cast $_result to object and append to our final results
$results[$i] = (object)$_result;
}
}
$stmt->close();
return
$results;
}
?>

<< Back to user notes page

To Top