This question already has an answer here:
PDO looping through and printing fetchAll
(1 answer)
Closed 7 years ago.
I did a query in php and all the results are stored in an object. For example
$query = "select * from some_table";
$sth = $dbc->query($query);
$results = $sth->fetchAll();
Therefore the results of the query is stored in $results and I have a property called name. How can I now loop through this object $results to change all the values of a certain property name of the object.
Assuming name is a public property:
for($i = 0; $i < count($results); $i++){
$results[$i]->name = ...;
}
Related
This question already has answers here:
How do I solve "Parameter must be an array or an object that implements Countable?" [duplicate]
(2 answers)
Closed 2 years ago.
I write this script in roder to verify if the sql empty or not:
if (isset($_GET['edit'])){
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("SELECT * FROM task WHERE id_task=$id") or die($mysqli->error());
$count = count($result);
if($count == 1){
$row = $result->fetch_array();
$nom_task = $row['name_task'];
$id_operation = $row['id_operation'];
$nom_operation = $row['name_operation'];
}
any suggetions to resove this please? the problem is in $count and $result?????
mysqli::query returns a mysqli_result object (see https://www.php.net/manual/en/mysqli.query.php)
That object is not countable (meaning it cannot be used as a parameter in the count function)
If you want to know the number of rows returned by your SQL request, use $num_rows property from that mysqli_result object :
$result = $mysqli->query('SELECT ...');
$count = $result->num_rows;
Also as a (very important) side note, your code is vulnerable to SQL Injection, please see : https://stackoverflow.com/a/601524
Hey try this code snippet:
if (isset($_GET['edit'])){
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("SELECT * FROM task WHERE id_task=$id") or die($mysqli->error());
if(!empty($result) && count($result) == 1){
$row = $result->fetch_array();
$nom_task = $row['name_task'];
$id_operation = $row['id_operation'];
$nom_operation = $row['name_operation'];
}
Simply check the array if it's empty or not before count check.
This question already has answers here:
Convert PDO resultset to array of objects
(5 answers)
Closed 2 years ago.
I´m trying to get all records from the database and then instantiate a new object with the data from each one:
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($results){
for ($i=0; $i<count($results); ++$i){
$strValues = '';
$values = array_values($results[$i]);
for ($j=0; $j<count($values); ++$j){//Extract the values to pass them as arguments to the constructor below
if ($j == 0) $strValues .= $values[$j];
else{
$strValues .= ',';
$strValues .= '"'.$values[$j].'"';
}
}
eval('$result['.$i.'] = new '.get_class($this->instance).'('.$strValues.');');
}
}
The problem is that the object type can vary depending on if I'm querying the users or labels databases, so the call to constructor may be new User(user_id, username, name, surname) or new Label(label_id, name, description, color). The code above runs on the ObjectMapper class, which on creation gets assigned an object type and stores an instance of it in the private instance variable. This way I can get the name of the required constructor with get_class($this->instance).
I finally managed to make it work using an eval as shown, but I've read that this is not a good practice and I would like to know of better and cleaner ways to do it.
This should do what you are trying to achieve. Do not use eval
PDO has plenty of useful fetch modes and they are described here https://phpdelusions.net/pdo/fetch_modes#FETCH_CLASS
$stmt = $this->pdo->prepare('SELECT * FROM '.$this->table.' ORDER BY '.$order.' ASC');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_CLASS, get_class($this->instance));
P.S. Remember to properly whitelist the table name and $order variable.
This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
How can I loop this table in PHP?
$query= "SELECT * FROM table1";
$select= mysqli_query($connection, $query);
$row = mysqli_fetch_array($select);
while ($row = mysqli_fetch_array("$select")) // line 21
{
echo $row["column1"];
}
I have updated the code and I get this error
Recoverable fatal error
: Object of class mysqli_result could not be converted to string on line 21
There are multiple issues with your current code.
You fetch the first row with $row = mysqli_fetch_array($select); (line 3), but you don't do anything with it. This means that the first result is discarded.
Your while loop attempts to loop over an incorrect variable ($query is a string, not the result-object), and you've quoted it into a string - you need to do it as you were with the first fetch (line 3).
You don't do anything inside your loop, so the results aren't printed. At the very least, you should print them with echo.
$query = "SELECT * FROM table1";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_array($result)) {
echo $row["column1"]."<br />\n";
}
This question already has answers here:
Resetting array pointer in PDO results
(7 answers)
Closed 8 years ago.
I need to loop through the results of a query a few times. After the first loop, I cannot go through the results again as the pointer is at the bottom. How can I make it return to the top? I dont want to run the query again as that is just going to use up more resources and return the same results.
$stmt = $conn->prepare("SELECT * FROM customers");
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$stmt->execute();
//This kind of loop will repeat elsewhere in the code
while($row = $stmt->fetch()){
//Do something here
}
while($row = $stmt->fetch()){
$rows[] = $row; //use $rows later
//Do something here with $row
}
This question already has answers here:
MySQLi equivalent of mysql_result()?
(12 answers)
Closed 10 months ago.
I am trying to convert a mysql script to mysqli and have hit a wall. I am trying to convert a mysql_result to mysqli however am unsure how to do this, below is my code
$_SESSION['num_user'] = mysql_result(mysqli_query($GLOBALS["___mysqli_ston"], "SELECT COUNT(*) FROM `members` WHERE mem_emailactivated = 1"), 0);
As weird as it is, there doesn't seem to be a way to fetch without prepare/execute.
$stmt = mysqli_prepare($GLOBALS['___mysqli_ston'], "SELECT COUNT(*) AS count ...");
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $count);
mysqli_stmt_fetch($stmt);
$_SESSION['num_user'] = $count;
You are mixing things up here. You wouldn't use mysql_result to get the result from a query using mysqli. you would instead use mysqli to iterate through the returned array and then store this array in the $_SESSION.
$result = $mysqli->query("call getUsers()");
if($result){
// Cycle through results
while ($row = $result->fetch_object()){
$user_arr[] = $row;
}
$result->close();
}
$_SESSION['num_user'] = $user_arr;