How to read "fetch(PDO::FETCH_ASSOC);" - php

I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.
For example, let’s say that I have this code:
$sql = "SELECT * FROM users WHERE user_id = :user_id";
$stmt = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.
How does this work?

PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => 'youremail#yourhost.com'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];

Loop through the array like any other associative array:
while($data = $datas->fetch(PDO::FETCH_ASSOC)){
print $data['title'] . '<br>';
}
or
$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
echo '<pre>' . $resultset . '</pre>';

Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary

PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.
You can access the name field like this: $user['name'].
I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name

To read the result you can read it like a simple PHP array.
For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return one tuple though. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.

Design Pattern "table-data gateway"
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
Print all row with column 'user_id' only
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
Print user_id = 1 with all column
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
Print user_id = 1 with column 'email and password'
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];

consider the following code script, will help.
$stm = $accountdb->query($sql);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
$number = $stm->rowCount();
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
header("Content-type: application/json");
echo '{"total" : "' . $number . '","records" : ' . $json . '}';

Related

mysqli_fetch_array() not producing an array

I can't seem to be able to place the resultset into an array and then use print_r to print out the array. Here's the script:
<?php
require( 'wp-load.php' );
$local = 'xxx';
$user = 'xxx';
$pass = 'xxx';
$data = 'xxx';
$testConnection = mysqli_connect($local,$user,$pass, $data);
if (!$testConnection) {
die('Error: ' . mysqli_connect_errno() . PHP_EOL);
}
echo 'Database connection working!';
global $wpdb;
$result = $wpdb->get_results ( "SELECT * FROM $wpdb->options" );
/* this is commented out but works
foreach ( $result as $row ) {
echo $row->option_id.'<br>';
}
*/
//PART NOT WORKING
$results = [];
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo "hello"; //never executes?????
$results[] = $row;
}
//$results has all that you need
print_r($results); //empty array???
$testClosed = mysqli_close($testConnection);
if ($testClosed) {
echo "closed";
}
?>
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo "hello"; //never executes?????
$results[] = $row;
}
Try removing the while statement out of there. Array is going to be given to you with mysqli_fetch_array . So just write it like this :
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$results[] = $row;
You could just access the indexes with $row[...] but still, up to you.
On the other hand :
On the documentation for the function there is such statement :
Return Value: Returns an array of strings that corresponds to the fetched row. NULL if there are no more rows in result-set
. So you might be calling a invalid table from your DB.

Is there any way to use the all fetched row's data from mysql database within a single dimentional php array function

This is the traditional way where I can fetch all rows with datas and run a while loop to get them one by one with mysqli_fetch_array() function.
$con = mysqli_connect(YOURLS_DB_HOST,YOURLS_DB_USER,YOURLS_DB_PASS);
mysqli_select_db($con,YOURLS_DB_NAME);
$users=mysqli_query($con,"SELECT * FROM users"));
while($user=mysqli_fetch_array($users))
{
$user['email']; $user['pass'];
}
Now the question is I have to insert all the rows with the respective datas into the bellow array. How is this possible. Rows will inserted one by one probably like the single line commented line. And non commented are actual data what I want.
$user_password = array(
'username2' => 'password2',
/* You can have one or more*/ 'login'=>'password',
// $user['email'] => $user['pass'],
)
I have done something and current state is
$con = mysqli_connect(YOURLS_DB_HOST,YOURLS_DB_USER,YOURLS_DB_PASS);
mysqli_select_db($con,YOURLS_DB_NAME);
$users=mysqli_fetch_assoc(mysqli_query($con,"SELECT email, pass FROM users"));
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass3[] = array(
$email => $pass,
'hguhfg'=> 'nhgudfhg',
);
}
$yourls_user_passwords = $user_pass3;
//print_r($user_pass4);
/*output Array ( [0] => Array ( [test#example.com] => test [hguhfg] => nhgudfhg ) [1] => Array ( [demo#example.com] => demo [hguhfg] => nhgudfhg ) ) but disired output is Array ( [test#example.com] => test [hguhfg] => nhgudfhg [demo#example.com] => demo); */
If you just want login and password :
$users = mysqli_query($con,"SELECT login, password FROM sughi_users"));
$user = array();
foreach ($users as $aUser) {
$user[$aUser['login']] = $aUser['password'];
}
After all of your suggestion i have done the program. Thank you everyone. Here us the perfect code.
$users = mysqli_query($con, "SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass3[] = array(
$email => $pass,
);
}
foreach($user_pass3 as $arr) {
foreach($arr as $key => $data) {
$user_pass[$key] = $data;
}
}
// print_r($user_pass);
$user_pass_final = $user_pass;
The [] notation on a variable makes it a dynamic array. So don't use array() after that. You can also pass a unique key inside the brackets if you prefer.
$users = mysqli_query($con, "SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
$email = $row['email'];
$pass = $row['pass'];
$user_pass_final[$email] = $pass;
}
print_r($user_pass_final);
Additionally you are double fetching, and fetching on an array which should fail so instead of:
$users=mysqli_fetch_assoc(mysqli_query($con,"SELECT email, pass FROM users"));
while ($row = mysqli_fetch_assoc($users)) {
You should assign the query return to $users:
$users=mysqli_query($con,"SELECT email, pass FROM users");
while ($row = mysqli_fetch_assoc($users)) {
Final note, passwords should NOT be stored in plain text. See https://security.stackexchange.com/questions/120540/why-shouldnt-i-store-passwords-in-plaintext
<?php
$servername = "localhost";
$username = "root";
$password = "";
$database = "test";
$conn = mysqli_connect($servername, $username, $password, $database); if (!($conn))
{
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT email,pass FROM users";
$result = mysqli_query($conn, $sql);
$newArray = array();
if (mysqli_num_rows($result) > 0)
{
/* loop for return all the fetched data one by one */
while($row = mysqli_fetch_assoc($result))
{
/* store the data from mysqli array in variable use same code for for as much as type of data you want*/
$email=$row["email"];
$password=$row["pass"];
/* you can also add some value manually into the same array like this */
$newArray['admin']= 'adminpass';
$newArray['test']= 'testpass';
/* You have to build one array variable which includes 2 type of data 1st one as array index and 2nd one as value */
$newArray[$email]= $password;
}
}
else
{
echo "0 results";
}
$conn->close();
/* print the array or store in another variable to use elsewhere. */
print_r($newArray);
/* or print indiviual data one by one like data1, data2 */
echo "<br>";
foreach($newArray as $x => $x_value)
{
echo "Email=" . $x . ", Password=" . $x_value;
echo "<br>";
}
/* this example shows email and password in plain text just for the special requirement of the project. It's recomended to not to use passwords in plain text and inside the code. */
//Credits gose to https://www.facebook.com/ansarali.molla.9
?>

How do i save a "name" from a table into a variable in PDO [duplicate]

I am trying to build a web application using PHP and I am using Memcached for storing user data from the database.
For example, let’s say that I have this code:
$sql = "SELECT * FROM users WHERE user_id = :user_id";
$stmt = $this->_db->prepare($sql);
$result = $stmt->execute(array(":user_id" => $user_id));
$user = $stmt->fetch(PDO::FETCH_ASSOC);
I am not really sure how to read the $user variable and get the data out of it. I will need to be able to read the email and password column.
How does this work?
PDOStatement::fetch returns a row from the result set. The parameter PDO::FETCH_ASSOC tells PDO to return the result as an associative array.
The array keys will match your column names. If your table contains columns 'email' and 'password', the array will be structured like:
Array
(
[email] => 'youremail#yourhost.com'
[password] => 'yourpassword'
)
To read data from the 'email' column, do:
$user['email'];
and for 'password':
$user['password'];
Loop through the array like any other associative array:
while($data = $datas->fetch(PDO::FETCH_ASSOC)){
print $data['title'] . '<br>';
}
or
$resultset = $datas->fetchALL(PDO::FETCH_ASSOC);
echo '<pre>' . $resultset . '</pre>';
Method
$user = $stmt->fetch(PDO::FETCH_ASSOC);
returns a dictionary. You can simply get email and password:
$email = $user['email'];
$password = $user['password'];
Other method
$users = $stmt->fetchall(PDO::FETCH_ASSOC);
returns a list of a dictionary
PDO:FETCH_ASSOC puts the results in an array where values are mapped to their field names.
You can access the name field like this: $user['name'].
I recommend using PDO::FETCH_OBJ. It fetches fields in an object and you can access like this: $user->name
To read the result you can read it like a simple PHP array.
For example, getting the name can be done like $user['name'], and so on. The method fetch(PDO::FETCH_ASSOC) will only return one tuple though. If you want to get all tuples, you can use fetchall(PDO::FETCH_ASSOC). You can go through the multidimensional array and get the values just the same.
Design Pattern "table-data gateway"
class Gateway
{
protected $connection = null;
public function __construct()
{
$this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
}
public function loadAll()
{
$sql = 'SELECT * FROM users';
$rows = $this->connection->query($sql);
return $rows;
}
public function loadById($id)
{
$sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
$result = $this->connection->query($sql);
return $result->fetch(PDO::FETCH_ASSOC);
// http://php.net/manual/en/pdostatement.fetch.php //
}
}
Print all row with column 'user_id' only
$gateway = new Gateway();
$users = $gateway->loadAll();
$no = 1;
foreach ($users as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
$no++;
}
Print user_id = 1 with all column
$user = $gateway->loadById(1);
$no = 1;
foreach ($user as $key => $value) {
echo $no . '. ' . $key . ' => ' . $value . '<br />';
$no++;
}
Print user_id = 1 with column 'email and password'
$user = $gateway->loadById(1);
echo $user['email'];
echo $user['password'];
consider the following code script, will help.
$stm = $accountdb->query($sql);
$result = $stm->fetchAll(PDO::FETCH_ASSOC);
$number = $stm->rowCount();
$json = json_encode($result, JSON_UNESCAPED_UNICODE);
header("Content-type: application/json");
echo '{"total" : "' . $number . '","records" : ' . $json . '}';

Passing multiple dimension array in PHP

MySql query returns me a multi-dimensional array :
function d4g_get_contributions_info($profile_id)
{
$query = "select * from contributions where `project_id` = $profile_id";
$row = mysql_query($query) or die("Error getting profile information , Reason : " . mysql_error());
$contributions = array();
if(!mysql_num_rows($row)) echo "No Contributors";
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[$cnt]['user_id'] = $fetched['user_id'];
$contributions[$cnt]['ammount'] = $fetched['ammount'];
$contributions[$cnt]['date'] = $fetched['date'];
$cnt++;
}
return $contributions;
}
Now I need to print the values in the page where I had called this function. How do I do that ?
change the function like this:
while($fetched = mysql_fetch_array($row, MYSQL_ASSOC))
{
$contributions[] = array('user_id' => $fetched['user_id'],
'ammount' => $fetched['ammount'],
'date' => $fetched['date']);
}
return $contributions;
Then try below:
$profile_id = 1; // sample id
$result = d4g_get_contributions_info($profile_id);
foreach($result as $row){
$user_id = $row['user_id']
// Continue like this
}

Echo-ing Only Available Database Result

I have this Associative Array :
$Fields = array("row0"=>"Yahoo ID", "row1"=>"MSN ID", "row2"=> "Gtalk ID");
on the other side, I have this SQL query :
SELECT YahooID, MSNID, GTalkID From UserTable WHERE Username = '$Username' LIMIT 1;
the result maybe vary, because some users only have Yahoo ID and some have others. for example if I have this result :
$row[0] = NONE //means YahooID = NONE
$row[1] = example#msn.com
$row[2] = example#gmail.com
then how to have this as an output (echo) :
MSN ID = example#msn.com
Gtalk ID = example#gmail.com
since Yahoo ID is not exist, then the result will be MSN and Gtalk only. 'MSN ID' and 'Gtalk ID' is variable from Associative Array, while 'example#msn.com' and 'example#gmail.com' from SQL result.
thanks!
$Fields = array();
while ($row = $result->fetch_assoc()) {
if (! empty($row[0])) $Fields['MSN ID'] = $row[0];
if (! empty($row[1])) $Fields['GTalk ID'] = $row[1];
if (! empty($row[2])) $Fields['Yahoo ID'] = $row[2];
}
foreach ($Fields as $k => $v)
{
echo "$k = $v" . PHP_EOL;
}

Categories