put php query in array - php

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;
}

Related

Not Getting Row From Mysqli

I am using mysqli to get the row but it is not giving me row, and there is no error in query.
$query="select * from members where useremail='$user_email' and password='$password'";
$result=$db->query($query);
$row = $db->fetch_array($result);
echo $row['id'];
My query Function
function query($query){
$result=mysqli_query($this->conn, $query);
if(!$result){
echo $this->err_msg = mysqli_error($this->conn);
return false;
}else{
return $result;
}
}
My fetch_array Function
function fetch_array($result){
return mysqli_fetch_array($result);
}
How can i get Row using mysqli ?
Change your original code to reflect bound parameters using mysqli, this is more secure and should work
$query="select * from members where useremail='$user_email' and password='$password'";
$result=$db->query($query);
$row = $db->fetch_array($result);
echo $row['id'];
to bound parameters using mysqli prepared statements
$query="select id from members where useremail=? and password=?"; // Don't use select *, select each column, ? are placeholders for your bind variables
$stmt = $connection->prepare($query);
if($stmt){
$stmt->bind_param("ss",$user_email,$password); // Bind in your variables, s is for string, i is for integers
$stmt->execute();
$stmt->bind_result($id); // bind the result to these variables, in the order you select
$stmt->store_result(); // Store if large result set, can throw error if server is setup to not handle more than x data
$stmt->fetch();
$stmt->close();
}
echo $id; // this would be same as $row['id'], $id now holds for example 5.
If you select multiple things, such as "SELECT id,name FROM...", then when you bind_result(..), just bind them n there. $stmt->bind_result($id,$name);
now $id and $name hold the column data for that row matching your query. If there would be multiple rows matching, instead of $stmt->fetch() you'd do
while($stmt->fetch()){ // just like while($row = $result->fetch_assoc()){}
echo $id;
echo $name
}

Preparing SQL query with multiple parameters (mysqli) [duplicate]

This is my simple query in php, using mysqli object oriented style:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$stmt->bind_result($name);
while($stmt->fetch()){
echo $name." ";
}
$stmt->free_result();
$stmt->close();
This works fine. I obtain the list of name retrieved from the select statement.
Now, inside the while I want use the $name variable as parameter for another query, but mysqli do not allow this, since I have to close the first query and then call the second query.
So I think I have to store the result of the first query and then iterate over the result calling a new query.
I have tried the following:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
//$stmt->bind_result($name);
$result = $stmt->store_result();
$stmt->free_result();
$stmt->close();
while ($row = $result->fetch_row())
{
echo $row[0]." ";
}
But this does not work. The code inside while is never reached.
N.B.: I want avoid the use of multi_query().
mysqli_stmt::store_result return a boolean. According to the doc it should be something like:
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($name);
while($stmt->fetch()){
//echo $name." ";
// try another statement
$query = "INSERT INTO usertable ...";
$stmt2 = $mysqli->prepare($query);
...
}
$stmt->free_result();
$stmt->close();
If this doesn't work you can fetch all rows first into an array and then looping that array again:
$stmt->execute();
$stmt->bind_result($name);
$names = array();
while($stmt->fetch()){
$names[] = $name;
}
$stmt->free_result();
$stmt->close();
foreach($names as $name) {
$query = "INSERT INTO usertable ...";
$stmt = $mysqli->prepare($query);
...
}
I have solved the problem:
$query = "SELECT name FROM usertable WHERE id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i', $id);
$id= $_GET['id'];
$stmt->execute();
$result = $stmt->get_result();
$stmt->free_result();
$stmt->close();
while ($row = $result->fetch_array(MYSQLI_NUM))
{
echo $row[0]." ";
}
Simply using get_result() and fetch_array()

Converting mysql functions to mysqli prepared statment keeping the same output

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){}

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

How to get variable from pdo query? Error showed

I am trying to get variable from pdo query but I got an error and could not figure it out. Error I get is PDO::query() expects parameter 1 to be string, object given.
// first I get variable, and when I echo variable I get good result.
$id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=$id");
$q=$conn->query($stmt);
while($row = $q ->fetch(PDO::FETCH_ASSOC)){
$kolicina=$row["Kolicina"];
}
echo $kolicina;
Use instead:
id=$_POST("kolicina");
$stmt=$conn->prepare("SELECT Kolicina FROM table1 where Kolicina=:id");
$stmt->execute(array('id' => $id));
the :id is binded to $id on the execute statement.
And to fetch the result use:
$stmt->fetch(PDO::FETCH_ASSOC);
First read here PHP MANUAL PDO
Second what you did there is wrong.
$id = $_POST['yourvarfromform'];
$stmt = $conn->prepare("SELECT * FROM table1 WHERE Kolicina = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_STR) // if it's string you can check on pdo manual because you can use int and others.
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $key => $value {
// Run Some Code Here
}
Change your code to be like this:
$stmt=$conn->prepare('SELECT Kolicina FROM table1 where Kolicina = :id');
$array = array('id' => $id);
$stmt->execute($array);
And you can fecth all results like this:
$result = $stmt->fetchAll();
print_r($result);
?>

Categories