Echo-ing Only Available Database Result - php

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

Related

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

mySQL get data intro an associative array

I am using the below code to get the users list from my db:
if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {
while ($row = $result->fetch_assoc()) {
$username[] = $row["user_name"];
$user_email[] = $row["user_email"];
$user_name[] = $row["name"];
$user_surname[] = $row["surname"];
$avatar[] = $row["avatar"];
}
$result->close();
}
But I get the below error:
Fatal error: [] operator not supported for strings
This is probably what you want to do:
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
// $rows is now an array that contains each individual row from your result set
You can then do whatever you want with that data, eg display it in a table or whatever.
foreach($rows as $user)
{
echo $user['user_name'] . ' - ' . $user['user_email'];
}
And so on
Your $username variable has been set as a string somewhere in the code before the codeblock you have posted. If you use $username=array(); you will loose that variable. I don't know if you need it or not.
Here is a better way to do :
$users = array();
while ($row = $result->fetch_assoc()) {
$users[] = array(
"username" => $row["user_name"],
"email" => $row["user_email"],
"name" => $row["name"],
"surname" => $row["surname"],
"avatar" => $row["avatar"]
);
}
And you can loop the users using foreach:
foreach($users as $user){
echo $user["username"];
echo $user["email"];
}
you should take an empty array befor loop if you want these into array. like this
if ($result = mysqli_query($mysqli, "SELECT user_name, name, surname, avatar, user_email FROM users")) {
$results=array();
while ($row = $result->fetch_assoc()) {
$results []=$row;
}
$result->close();
}
other wise you should remove []
You can do this also -
$user_data = array();
while ($row = $result->fetch_assoc()) {
$user_data[] = $row;
}
By this you can get all the data in a single array. The keys will be the same as database fields.

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
}

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

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

Get value from an array

I have a private message system and I have this function that returns the IDs of all the users in the conversation (except the sender):
function findOtherUsersInConversation($conversation_id) {
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
while ($row = mysql_fetch_array($query)) {
$user_id = $row['user_id'];
print_r($user_id);
}
}
print_r return the Ids (for instance id100 and id 101)like this:
100101//which is not what i'm trying to do
I have another function that find the username in the database so for each user id I would like to get their usernames in this format:
echo usernameFromId($user_id)// this should echo out all the username like this (user a, user b, user c)
I think I have to do a foreach loop but I can't think how.
Try this:
function findOtherUsersInConversation($conversation_id){
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
$users = array();
while ($row = mysql_fetch_array($query)) {
$users[] = usernameFromId($row['user_id']); // fetch user name and add it to array
}
return implode(', ', $users); // return a string separated by commas
}
findOtherUsersInConversation(10); // conversation id 10
Try like this
function findOtherUsersInConversation($conversation_id) {
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id = '$conversation_id' AND user_id !=$sender");
$cnt=0;
while ($row = mysql_fetch_array($query)) {
$user_id = $row['user_id'];
if($cnt==0):
$comma_separated .=$user_id;
else:
$comma_separated .=",".$user_id;
endif;
$cnt++;
}
return $comma_separated
}
$getID=findOtherUsersInConversation(10);
$arrayID= explode( ',', $getID);// split string from comma(,)
print_r($arrayID);// print all ID's as you want
May this will Help you.
function findOtherUsersInConversation($conversation_id){
$sender = findMessageSenderId($conversation_id);
$query = mysql_query("SELECT user_id FROM message_partecipant WHERE conversation_id ='$conversation_id' AND user_id !=$sender");
$usernameArr = array();
while ($row = mysql_fetch_array($query)) {
$user_id= $row['user_id'];
array_push($usernameArr, usernameFromId($user_id));
}
$comma_separated = implode(",", $usernameArr);
echo $comma_separated;
}
If you want to view the array only for your Information try:
var_dump($array);
otherwise try it in a foreach to output your array:
foreach($array as $var){
echo $var;
}

Categories