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.
Related
When I echo the variable $contact_username I can see the response in my Android logcat in the form (5 values, which is the correct amount): +11+22+33+44+55.
I'm having trouble returning this as a json array so I can see it in the form,
[{"contact_phonenumber":"+11"},{"contact_phonenumber":"+22"},{"contact_phonenumber":"+33"},{"contact_phonenumber":"+44"},{"contact_phonenumber":"+55"}]
My Php file to echo $contact_username as above is like :
//stuff here
foreach ($array as $value)
{
// stuff here
$result = $stmt->get_result();
$contact_username = "";
while ($row = $result->fetch_assoc()) {
$contact_username = $row['username'];
}
echo $contact_username;
So echoing $contact_username; gives me +11+22+33+44+55 which I want to return as a JSON Array.
The closest I can get is with the code below but it gives me :
[][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][][{"contact_phonenumber":"+11"}][][][][][][][][][{"contact_phonenumber":"+22"}][][][] etc... etc...
How can I get it as a JSON Array, and without the empty brackets? Here is my attempt but it's obviously not correct:
//stuff here
foreach ($array as $value)
{
// stuff here
$result = $stmt->get_result();
$results = [];
$contact_username = "";
while ($row = $result->fetch_assoc()) {
$contact_username = $row['username'];
array_push($results,['contact_phonenumber' => $contact_username] );
}
$json2 = json_encode($results);
echo $json2;
EDIT : I'm posting the entire code of my PHP file below
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//***************************************************
require('dbConnect.php');
//this is the user_id in the user table
$Number = $_POST['phonenumberofuser'];
// get the username of the user in the user table, then get the matching user_id in the user table
// so we can check contacts against it
$query = "SELECT * FROM user WHERE username = ?";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param('s', $Number) or die ("MySQLi-stmt binding failed ".$stmt->error);
$stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//this is the user_id in the user table of the user
$user_id = $row["user_id"];
}
//post all contacts in my phone as a JSON array
$json = $_POST['phonenumberofcontact'];
//decode the JSON
$array = json_decode($json);
//We want to check if contacts in my phone are also users of the app.
//if they are, then we want to put those phone contacts into the contacts table, as friends of user_id , the user of the app
$query = "SELECT * FROM user WHERE username = ?";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param('s', $phonenumberofcontact) or die ("MySQLi-stmt binding failed ".$stmt->error);
$contacts = [];
//for each value of phone_number posted from Android, call it $phonenumberofcontact
foreach ($array as $value)
{
$phonenumberofcontact = $value->phone_number;
$stmt->execute() or die ("MySQLi-stmt execute failed ".$stmt->error);
//store the result of contacts from the user's phonebook (that is, the result of the above query, $stmt) that are using the app
$result = $stmt->get_result();
//In this while loop, check the $phonenumberofcontact in the user's phonebook and who are users of the app against
//the user's contacts table. Put the shared contacts in the contacts table for that user.
while ($row = $result->fetch_assoc()) {
$contacts[]["contact_phonenumber"] = $row['username'];
}
echo json_encode($contacts);
}
$stmt->close();
?>
$contacts = [];
foreach ($array as $value)
{
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$contacts[]["contact_phonenumber"] = $row['username'];
}
}
echo json_encode($contacts);
...will produce: [{"contact_phonenumber":"+11"},{"contact_phonenumber":"+22"},{"contact_phonenumber":"+33"},{"contact_phonenumber":"+44"},{"contact_phonenumber":"+55"}].
Instead of :
$contacts = [];
foreach ($array as $value)
{
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
$contacts[]["contact_phonenumber"] = $row['username'];
}
}
It should be :
$results = array();
foreach ($array as $value)
{
$result = $stmt->get_result();
if(!empty($row['username'])) {
$results[] = array('contact_phonenumber' => $row['username']);
}
}
My table's name is userdetails, it has four attributes named name, username, mobile and password. I want to get all the mobile numbers and store it in an array using php.
I have used the following php code
if($_SERVER['REQUEST_METHOD']=='GET'){
require_once('dbConnect.php');
$mobile = $_GET['mobile'];
$sql = "SELECT MOBILE FROM USERDETAILS";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"MOBILE"=>$res['MOBILE']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
but all I am getting is the first entry of the database.
Please help.
You should loop through the records by doing the following:
$result = [];
while ($array = mysqli_fetch_array($r)) {
$result[] = $array['MOBILE'];
}
echo json_encode($result);
For getting all number of column use while loop as
$jsonData = array();// initialized you array
while ($array = mysqli_fetch_array($r,MYSQLI_ASSOC)) {// add MYSQLI_ASSOC to get associative array
$jsonData[] = $res['MOBILE'];// store data into array
}
echo json_encode($jsonData);// convert in into json
Try this:
$result = mysqli_query($con,$sql);
$mob = Array();
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$mob[] = $row['MOBILE'];
}
I need to encode a table content to JSON in order to insert it into a file.
The output has to be as following :
{
"name1":[{"id":"11","name":"name1","k1":"foo","k2":"bar"}],
"name2":[{"id":"12","name":"name2","k1":"foo","k2":"bar"}],
}
Indeed, each JSON "line" corresponds to the content of the mysql row and the name of each JSON array is the name of the 'name' column.
The only thing I could manage for the moment is this :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
$index = 0;
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$index] = $row;
$index++;
}
echo json_encode($return_arr);
And here is the output I get :
[
{"id":"11","name":"name1","k1":"foo","k2":"bar"},
{"id":"12","name":"name2","k1":"foo","k2":"bar"},
]
Thanks a lot !!!
UPDATED
Working code :
$return_arr = array();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$return_arr[ $row['nom_appart'] ][] = $row;
}
echo json_encode($return_arr);
}
You were close. I noticed you want final output to be an object not an array, because the outer brackets are {} not []. So you need a different object type, and you need to use each row's name as the key for storing that row.
$return_obj = new stdClass();
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$name = $row['name'];
$return_obj->$name = [$row]; // for PHP < 5.4 use array($row)
}
echo json_encode($return_obj);
This loop is enough, to create the desired JSON:
$return_arr = array();
while ($row = mysql_fetch_assoc($result)) {
$return_arr[$row['name']][] = $row; #or $return_arr[$row['name']] = [$row];
}
echo json_encode($return_arr);
I was working on it a lot of time and Create mash/mysql-json-serializer package.
https://github.com/AndreyMashukov/mysql-json-serializer
You can select Json_array of json_objects and etc. It support ManyToMany, oneToMany, manyToOne relations
SELECT JSON_ARRAYAGG(JSON_OBJECT('id',est_res.est_id,'name',est_res.est_name,'advert_groups',(SELECT JSON_ARRAYAGG(JSON_OBJECT('id',adg.adg_id,'name',adg.adg_name)) FROM advert_group adg INNER JOIN estate est_2 ON est_2.est_id = adg.adg_estate WHERE est_2.est_id = est_res.est_id))) FROM (SELECT * FROM estate est LIMIT 1 OFFSET 2) est_res
<?php
$sql = "SELECT * FROM bo_appart";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$return_arr[] = $row;
}
echo json_encode($return_arr);
?>
I have a SELECT query that results in something like this:
USER_ID: 000030 USERNAME: Oprah RATING: 5
USER_ID: 000033 USERNAME: Pitbull RATING: 8
What I need is to display it in this form:
[[{"USER_ID":"000030","USERNAME":"Oprah","RATING":"5"},{"USER_ID":"000033","USERNAME":"Pitbull","RATING":"8"}]]
Generally I get this desired result with this SELECT:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$output[] = $row;
}
}
print(json_encode($output));
But this time I had to get the result in this form:
try {
$stmt = $conn->prepare("SELECT USER_ID, USERNAME, RATING FROM table");
$stmt -> execute(array($userid));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//$output[] = $row;
$row2[$i][$j] = $row['USER_ID'];
$j++;
$row2[$i][$j] = $row['USERNAME'];
$j++;
$row2[$i][$j] = $row['RATING'];
$i++;
$j=0;
}
}
How can I convert it into the desired form or form the query to produce it?
I tried these:
print(json_encode($row2));
[["000030","Oprah","5"],["000033","Pitbull","8"]]
$output[] = $row2;
print(json_encode($output));
[[["000030","Oprah","5"],["000033","Pitbull","8"]]]
For json_encode() to produce a json string that includes the associative indices, they need to be in the array you are encoding. If the indices are 0, 1, 2, etc., the indices will not show up in the json string.
Try this:
$i=0;
while(...) {
$row2[$i]['USER_ID'] = $row['USER_ID'];
$row2[$i]['USERNAME'] = $row['USERNAME'];
$row2[$i]['RATING'] = $row['RATING'];
$i++;
}
...
print_r(json_encode($row2));
Consider this PHP snippet for clarification.
Alternative methods of building array:
while(...) {
$row2[] = array(
'USER_ID' = $row['USER_ID'],
'USERNAME' = $row['USERNAME'],
'RATING' = $row['RATING']
);
}
// OR
$i=0;
while(...) {
foreach ($row as $key => $val) {
$row2[$i][$key] = $val;
}
$i++;
}
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$output[] = array("USER_ID" => $row["USER_ID"],
"USERNAME" => $row["USERNAME"],
"RATING" => $row["RATING"],
);
}
print(json_encode($output));
I get an array of values returned from the following function:
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
I now want to use these values in a new function, where each "user_id" is used to collect text from the database through this function:
function get_text($writer) {
$writer = mysql_real_escape_string ($writer);
$sql = "SELECT * FROM `text` WHERE user_id='$writer' ORDER BY timestamp desc";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
However the returned value from the first function is an array, and as I've learnt the hard way, arrays cannot be treated by "mysql_real_escape_string".
How can I make the second function handle the values that I got from the first function?
Any responses appreciated.
Thank you in advance.
Your first mistake is to use mysql_fetch_assoc when only selecting one column. You should use mysql_fetch_row for this. This is likely going to fix your primary problem.
Could look like this:
$subs = get_subscribitions($whateverId);
$texts = get_text($subs);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_row($result)) {
$user_id = $row['user_id'];
$rows[$user_id] = $user_id;
}
mysql_free_result($result);
return $rows;
}
function get_text($writer) {
$writers = implode(",", $writer);
$sql = "SELECT * FROM `text` WHERE user_id IN ({$writers}) ORDER BY timestamp DESC";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row;
}
mysql_free_result($result);
return $rows;
}
This will save you a lot of time, because you can get all data from 'text' in one statement.
The solution is to avoid placing arrays in your $rows array in the first function. Instead of:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
try:
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
This will place only the value from column 'user_id' in the $rows array.
In order to use the second function you must iterate over the array returned from the first one. Something like this could work for you:
$user_subscriptions = get_subscribitions($user);
foreach($user_subscriptions as $subscription) {
$texts = get_text($subscription['user_id']);
foreach($texts as $text) {
// do something with the fetched text
}
}
As George Cummins says,
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row['user_id'];
}
and, to speed up the second function:
function get_text($writer)
{
$sql = "SELECT * FROM `text` WHERE user_id in (".implode(',',$writer).") ORDER BY timestamp desc";
$rows = array();
if ($result = mysql_query($sql))
{
while ($row = mysql_fetch_assoc($result))
{
$rows[] = $row;
}
mysql_free_result($result);
}
return $rows;
}
The change to the query means that you only do one in total rather than one for each ID thus removing the time taken to send the query to the server and get a response multiple times. Also, if the query fails, the function returns an empty array
Use :
string implode ( string $glue , array $pieces )
// example, elements separated by a comma :
$arrayasstring = impode(",", $myarray);
function get_subscribitions($user)
{
$user = mysql_real_escape_string ($user);
$sql = "SELECT 'user_id' FROM `subscribe` WHERE subscriber = '$user'";
$result = mysql_query($sql);
$row = mysql_fetch_row($results);
mysql_free_result($result);
return intval($row['user_id']);
}
it return only the user id you can used it in the 2nd function