Converting mysql functions to mysqli prepared statment keeping the same output - php

I'm currently going thorough a site and replacing all the functions which used to return mysql_fectch_array() results, which are put into while loops elsewhere. I'm trying to make them return the same data in the same format but by using mysqli prepared statements output. I have been successful with the code below in producing the same formatted output for single row results.
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT * FROM email_setting WHERE user_id = ? LIMIT 1");
$stmt->bind_param("i", $this->user);
$stmt->execute();
$stmt->bind_result(
$row['email_id'],
$row['user_id'],
$row['news'],
$row['new_message'],
$row['new_friend'],
$row['rule_assent'],
$row['agreement_ready'],
$row['agreement_all_assent'],
$row['time_cap'],
$row['donations']
);
$stmt->store_result();
$stmt->fetch();
$stmt->close();
return $row;
}
But how can I get this code to work when it returns more than one row? I want it to be produce the same result as if I had written:
return mysql_fetch_array($result);
Is it possible?

Consider the following adjustment, passing query results into an associative array:
public function get_email_settings(){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT email_id, user_id, news, new_message,
new_friend, rule_assent, agreement_ready,
agreement_all_assent, time_cap, donations
FROM email_setting
WHERE user_id = ? ");
$stmt->bind_param("i", $this->user);
$stmt->execute();
// CREATE RETURN ARRAY
$row = [];
// OBTAIN QUERY RESULTS
$result = $stmt->get_result();
// ITERATE THROUGH RESULT ROWS INTO RETURN ARRAY
while ($data = $stmt->fetch_assoc()) {
$row[] = $data;
}
$stmt->close();
return $row;
}
You will notice I explicitly select the query's fields to avoid an indeterminate loop through query results.

Ok I have managed to get it to work without using get_result()
This is how I did it with alot of help from Parfait and Example of how to use bind_result vs get_result
function saved_rules($user){
$stmt = $this->cn->stmt_init();
$stmt->prepare("SELECT R.rule_id, R.rule_title
FROM Savedrules S
LEFT JOIN Rule R
ON S.saved_rule_id = R.rule_id
WHERE S.saved_user_id = ?");
$stmt->bind_param("i", $user);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($id, $rule_title);
while ($stmt->fetch()) {
$result[] = Array("rule_id"=>$id,"rule_title"=>$rule_title);
}
$stmt->free_result();
$stmt->close();
return $result;
}
Its not exactly the same output as using a mysql_fetch_array() so where it is used I have to change the loop to:
foreach($saved_rules AS $row){}
from
while ($row = mysql_fetch_array($saved_rules){}

Related

Why is the $row array not populated with query values

I know my conn is good and the direct SQL produces the desired output, but my $row variable is not getting values from the -> FETCH()
Similar fetch() working in other code blocks
$stmt = $conn->prepare("SELECT firstname,vcode FROM users WHERE email = ? AND verifydate IS NULL AND active = 0");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows === 1) {
$row = $stmt->fetch();
$firstname = $row[0];
$vcode = $row[1];
}
No error msgs -- simply $row[] values empty
In mysqli, $stmt->fetch() doesn't return the row, it just returns true or false to indicate whether a row could be fetched. You need to use $stmt->fetch_row() to get a numerically-indexed row, or $stmt->fetch_assoc() to get an associative array.
$stmt->fetch() is used along with $stmt->bind_result(), e.g.
$stmt->bind_result($firstname, $vcode);
$stmt->fetch();
If you see similar code that works in other applications, they must be using PDO rather than mysqli.

How to fetch data from database using prepare statement in php?

I have a database in which I have user_id & associated_id.There can be multiple associated_id for a single user_id. Now I want to fetch all the associated_ids into a single array. I have tried this method but don't know how to get them in array.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
$stmt->bind_param("s", $user_id);
if ($stmt->execute())
{
while ($stmt->fetch())
{
//what to write here
}
//echo var_dump($user);
$stmt->close();
}
Try this:
$stmt = $mysqli->prepare("SELECT associated_id FROM my_contacts WHERE user_id = ?")) {
$stmt->bind_param('s', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($associated_id);
$stmt->fetch();
The results will be stored in the $associated_id array.
You can bind parameters like this and use fetchall method to get all the results in a array
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = :user_id");
$stmt->bind_param(":user_id", $user_id, PDO::PARAM_INT);
if ($stmt->execute())
{
$result = $stmt->fetchall(PDO::FETCH_ASSOC);
//echo var_dump($user);
$stmt->close();
}
According to your code you used mysqli.
$stmt = $this->conn->prepare("SELECT * FROM my_contacts WHERE user_id = ?");
if($stmt->execute()){
$result = $stmt->get_result();
if($result->nom_rows > 0){
while($row = $result->fetch_assoc()){
var_dump($row)
}
}else{
echo "Sorry NO data found";
}
}else{
echo "Some thing is wrong";
}
here you can't used $stmt->bind_result(); instead of use $stmt->get_result()
$stmt->bind_result(); is only used when you define field in select query
with * you need to used $stmt->get_result()
refer this link for more information
Example of how to use bind_result vs get_result

put php query in array

I've a little problem, I've a query and i'would like that the result will go in an array.
function disponibilita($data) {
$this->sql_open();
$db=$this->db;
$sql="SELECT id FROM turni WHERE date='$data'";$stmt=$db->prepare($sql);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
printf ("%s", $id);
}
} `
printf stamp the right results, how to put into array the results of this dbquery?
Have a look at PDOStatement::fetchAll for PDO
, or check out mysqli_result::fetch_all for mysqli
function disponibilita($data) {
$this->sql_open();
$db=$this->db;
$sql="SELECT id FROM turni WHERE date='$data'";
$stmt=$db->prepare($sql);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC); // for PDO
$results = $stmt->fetch_all(MYSQLI_ASSOC); // for mysqli
return $results;
}

mysqli returning null values

im trying to get data from my DB but all i get is null values.
I know that the query isnt empty because i get values from inside my if($stmt->num_rows > 0)
code.
When i run my query on my phpmyadmin i also get good results.
This is my code thanks for helping:
$sql = "SELECT register_date FROM personal WHERE user_id = ?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('s', $user_id);
$user_id = $_GET['user_id'];
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($register_date);
if($stmt->num_rows > 0)
{
$response["date"] = $register_date;
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
Try
$stmt->bind_result($register_date);
$stmt->execute();
$stmt->store_result();
$stmt->fetch();
echo $register_date;
Please read bind_result doc
Your code is a bit mixed up, you'll need to define your variables (in this case $user_id) before using them.
I suggest moving to PDO rather than using MySQLi.

fetch() not returning first row

I am trying to update code that has been written using prepared statements. This is my first time using them and I am having difficulty retrieving all the results. When I use a direct SQL statement, it works so I don't think that's the problem.
The code will not return any results until there are at least two that match the query, then it will return all but the first row. I tried using fetchAll, but that gives different error about a call to an undefined method.
Thanks in advance for any help that you can provide. If it's not to much to ask, please provide example or reference I can refer to and complete my understanding.
function html_competitive_make_gallery ($init) {
global $USER;
$user_id = $USER->id;
$page_name = 'competitive';
$base_name = $init['base_name'];
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->bind_param('is', $user_id, $page_name);
$stmt->execute();
$stmt->bind_result($form_id,$community_id);
$stmt->fetch();
$stmt->close();
$sql = "SELECT data FROM tester WHERE type= '".$base_name."'
AND form_id= '".$form_id ."' AND community_id= '". $community_id ."' LIMIT 5";
$stmt = $link->prepare($sql);
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch();
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
$html[]='</div>';
return implode ( $html);
}
You're running fetch() before entering your loop, hence dropping the first row of your results:
$stmt->execute();
$stmt->bind_result($data);
$stmt->fetch(); // <<< THIS LINE SHOULD NOT BE HERE
$html[]='<div class="gallery" style ="width:100%;height:30%;overflow:hidden;">';
while ($stmt->fetch()){
echo $data;
}
$stmt->close();
Try this:
while ($data = $stmt->fetch()){
echo $data;
}
$stmt->close();
Your main problem is called "mysqli".
You will face such problems as long as you're using mysqli with prepared statements.
Just quit it and use PDO:
function html_competitive_make_gallery ($init) {
global $USER;
global $link;
$sql_pre = "SELECT form_id, community_id FROM frm_root WHERE user_id = ?
AND page_name = ? ORDER BY last_modified_date DESC LIMIT 1";
$stmt = $link->prepare($sql_pre);
$stmt->execute(array($USER->id, 'competitive'));
return $stmt->fetch();
}

Categories