PHP and PDO from procedural to OOP - empty object [duplicate] - php

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
So, right now I have a PHP function that utilizes PDO to return the first row of a specific table. That works fine, but I want to return all of the information, while being able to organize it all.
I have the table zip__admins and I'm trying to return the first_name and last_name from the table. With this information, I have a button on the login page asking the user to select their name (each person gets their own button) to sign in. As of now, I'm returning one result, instead of two results. How can I modify the below code to return two results, and input the data into a templating parameter.
final public function fetchAdminInfo() {
global $zip, $db, $tpl;
$query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$tpl->define('admin: first_name', $result['first_name']);
$tpl->define('admin: last_name', $result['last_name']);
}
Here is my table:
![SQL Table][1]

You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}

Related

PHP Get the class constructor dynamically and call it to create a new instance [duplicate]

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.

Extracting data from MYSQL and storing it into a variable in PHP [duplicate]

This question already has answers here:
Single Value Mysqli [duplicate]
(8 answers)
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 2 years ago.
I am having trouble extracting information from a table I have created in MYSQL. I am trying to extract the last entry id number of an individual and want to store it into a variable called $person_id.
So far, I have the following:
$res = mysql_query("SELECT max(person_id) FROM Persons;");
$person_id= mysql_query($res,$conn);
echo $person_id;
Nothing shows up when I try to print the variable name person_id.
The connection to the database works fine since I am able to insert data from a form I created. Any advice?
mysql_query was deprecated in PHP 5.5.
It will return a resource on success, or FALSE on error.
So, instead of echo, you could first try a var_dump($person_id).
Source : https://www.php.net/manual/en/function.mysql-query.php
First, avoid using mysql this extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used. Now back to your question, you are printing out the wrong value, your query using mysqli should look like this
$res = "SELECT max(person_id) FROM Persons;";
$person = mysqli_query($conn, $res);
echo $person;
this will return nothing because the result is an array(mysqli object) it cannot be converted to string just like that but, using print_r we can print out the value of person as follows
print_r($persons);
you should get something like this
mysqli_result Object ( [current_field] => 0 [field_count] => count [lengths] => [num_rows] => rows [type] => 0 )
the count and rows represents, depending on the results the number of fields and rows used in the query.
To print out the $person variable correctly, as in your query above it should be
$res = "SELECT max(person_id) FROM Persons;";
$result = mysqli_query($conn, $res);
//fetch the database values as an asscoiative array
while($row = mysqli_fetch_assoc($result))
{
$person_id = $row['person_id'];
}
echo $person_id;
this should print the value you wanted
You must have got some error because you are missing something here.
Thats how it should work for you.
$res = "SELECT max(person_id) FROM Persons";
$result = mysql_query($res,$conn);
list($person_id) = mysql_fetch_row($result);
echo $person_id;

Return MYSQLi Prepared Statement Query and Bind Results an an Array [duplicate]

This question already has answers here:
How to fetch all in assoc array from a prepared statement?
(4 answers)
Closed 2 years ago.
I want to put the result of a mysqli prepared statement into an array and return the array for use in another page.
The code is presented below.
function getPermission($mysqli , $email) {
if ($stmt = $mysqli->prepare("SELECT m.email , g.permission
FROM members m
INNER JOIN members_groups q ON m.member_id = q.member_id
INNER JOIN groups g on q.group_id = g.group_id
WHERE email = ?"))
{
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
// get variables from result.
$stmt->bind_result($user_email, $user_perms);
while ($stmt->fetch()) {
echo ' ID: '.$user_email; //prints the results.
}
}
}
I want to place the query results into an array and return the array.
Note: Am using a wamp server with php and mysql in windows 7. I tried to use the $stmt->getresults method, but it returns nothing.
You could try to store it in an array, one by one, in your loop:
$results = array();
while ($stmt->fetch()) {
$results[] = array(
"email" => $user_email,
"perms" => $user_perms
);
}
return $results;
If you need this array in another file, where you include this function, this will work, but if you need it in another request, PHP will have to run this code again to have the array filled.
If you need this array during the session, then consider putting the result in a session variable:
$_SESSION['myarray'] = $results;
Then in the function, first check if the above session variable is set, and if so, immediately return that value. Only when it is not yet set, you perform the rest of the function.

Object can't be converted to a string in MySQLi PHP [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.
You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.

PDO Return All Rows [duplicate]

This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
So, right now I have a PHP function that utilizes PDO to return the first row of a specific table. That works fine, but I want to return all of the information, while being able to organize it all.
I have the table zip__admins and I'm trying to return the first_name and last_name from the table. With this information, I have a button on the login page asking the user to select their name (each person gets their own button) to sign in. As of now, I'm returning one result, instead of two results. How can I modify the below code to return two results, and input the data into a templating parameter.
final public function fetchAdminInfo() {
global $zip, $db, $tpl;
$query = $db->prepare('SELECT first_name, last_name FROM zip__admins');
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
$tpl->define('admin: first_name', $result['first_name']);
$tpl->define('admin: last_name', $result['last_name']);
}
Here is my table:
![SQL Table][1]
You need to use fetchAll()
$result = $query -> fetchAll();
foreach( $result as $row ) {
echo $row['first_name'];
echo $row['last_name'];
}

Categories