I'm able to get the response from MySQL server, but I can't seem to put it in a variable
$filmNameList2 = [];
require('connect.php');
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
$json_array = array();
while($row=mysqli_fetch_array($result))
{
$json_array[] = $row;
// print_r($row); outputs Array ( [0] => Abruptio [title] => Abruptio [1] => (2019) [year] => (2019) )
}
$filmNameList2[] = $json_array->array[0]->array[0]->title;
// I have tried json_array->array[0]->title; json_array->title;
print_r($filmNameList2);
result that I get :
Array ( [0] => )
$filmNameList2 = array();
require('connect.php');
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
while($row=mysqli_fetch_array($result))
{
$object = array(
'title' => $row[0],
'year' => $row[1]
);
array_push($filmNameList2 , $object );
}
echo json_encode($filmNameList2);
print_r($filmNameList2);
try this code...
$query = "SELECT `title`,`year` FROM `filmList` WHERE year=' (2019)'";
$result = mysqli_query($connect, $query) or die(mysqli_error($connect));
$json_array = array();
while($row=mysqli_fetch_object($result))
{
$json_array[] = $row;
}
echo json_encode($json_array);
print_r($json_array);
$filmNameList2[] = $json_array[0]['title'];
Access the first row, then the title element in it.
Related
This question already has answers here:
mysqli_fetch_array returning only one result
(3 answers)
Closed 3 years ago.
In $result should be all of users from datebase, but it takes only first person and shows error.
My php code:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
require_once 'connect.php';
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = array();
$result['osoby'] = array();
$row = mysqli_fetch_assoc($response);
$index['name'] = $row['imie'];
$index['surname'] = $row['nazwisko'];
array_push($result['osoby'], $index);
$result['success'] = "1";
echo json_encode($result);
}
Its giving you 1 record because you are only printing 1 record,
Using $row = mysqli_fetch_assoc($response); will always give you last row if you not use loop here.
You need to use while loop to get all rows like:
<?php
$i = 0;
$result = array(); // initialize
while($row = mysqli_fetch_assoc($response)){
$result[$i]['name'] = $row['imie'];
$result[$i]['surname'] = $row['nazwisko']; // store in an array
$i++;
}
$finalResult['osoby'] = $result; // storing as you need
$finalResult['success'] = "1"; // no idea about this but adding this also
echo json_encode($finalResult); // encode with json
?>
You can loop the result-set and append an array of your values to the $result array.
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => []];
while ($row = mysqli_fetch_assoc($response)) {
$result['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
$result['success'] = "1";
echo json_encode($result);
If you have the mysqlnd driver installed, you can also use mysqli_result::fetch_all() method
$response = mysqli_query($conn, "SELECT imie, nazwisko FROM users");
$result = ['osoby' => mysqli_fetch_all($response, MYSQLI_ASSOC)];
$result['success'] = "1";
echo json_encode($result);
You have to loop the result array.
$resultJson = array();
$resultJson['osoby']=array()
$query = "SELECT imie,nazwisko FROM users";
$result = $mysql->query( $query );
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
// fetch information out of the $row..
$resultJson['osoby'][] = ['name' => $row['imie'], 'surname' => $row['nazwisko']];
}
}
print json_encode($resultJson);
I am Using Following code php array to encode Json
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data = $row;
}
echo json_encode($data);
}
IT gives Me result like
{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}
But I wanted To result like
{"SignIn":[{"id":"26","fname":"Shankar","lname":"Salunkhe","category_name":"2"}],"errors":[],"totalNumberOfRecords":1,"responseCode":"00000"}
How Can I do That
Or Suggest Me any other Method to do that
You need to do something like below to get the desired output.
$query = "SELECT * FROM register WHERE email='$email'AND password='$password'AND status!='0'";
$result = mysql_query($query) or die('Errant query: ' . $query);
$numResults = mysql_num_rows($result);
if ($numResults > 0)
{
$data = array();
while ($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
$result = ['SignIn' => $data, 'totalNumberOfRecords' => $numResults, 'errors' => [], 'responseCode' => 0000];
echo json_encode($result);
exit;
}
You have to store all information in a array to get what you want.
For example,
$data = array("id" =>"26","fname"=>"Shankar","lname"=>"Salunkhe","category_name"=>"2");
$array = array("SignIn" => $data, "errors" => [], "totalNumberOfRecords" => 1,"responseCode" => "00000");
$result = json_encode($array);
I'm working on a project, where the logged in user should be able to post notes on the homepage, and being logged in the certain user's notes should be printed above the new note form.
I've written a function for that, where the mysqli_query recognizes all the 6 entries I have, but the mysqli_fetch_assoc prints only the first note out of 6. What could I do wrong? Here is my code:
<?php
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
//mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 6 [type] => 0 )
confirm_query($result);
$row = mysqli_fetch_assoc($result);
//Array ( [content] => First! ) = it only shows the very first element
return $row;
}
?>
<?php
$notes_set = find_notes_by_id($userRow['id']);
foreach($notes_set as $note){
echo $note;
echo "<br />";
}
?>
You can get all results like so:
$arr = $result->fetch_all(MYSQLI_ASSOC);
Or use a while loop:
while($row = $result->fetch_assoc()){
echo $row['content'] . '<br />';
}
1.You need to iterate over your result-set object through while()
2.Save all your data to an array and then return that array to get all records
like below:-
<?php
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = "SELECT `content` FROM `notes` WHERE `user_id` = $safe_user_id";
$result = mysqli_query($connection, $query);
confirm_query($result);
$final_data = array(); // create an array
while($row = mysqli_fetch_assoc($result)){ // iterate over the result-set object to get all data
$final_data[] = $row; //assign value to the array
}
return $final_data; // return array
}
?>
Now:-
<?php
$notes_set = find_notes_by_id($userRow['id']);
print_r($notes_set) ; // print result to check array structure so that you can use it correctly in foreach
foreach($notes_set as $note){
echo $note['content'];
echo "<br />";
}
?>
Instead declaring $connection as global pass the $connection variable to the function which would be a efficient way and get the result as array
<?php
function find_notes_by_id($user_id,$connection) {
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
confirm_query($result);
$data = array(); // create an array
while($row = mysqli_fetch_assoc($result)){
$data[] = $row;
}
return $data;
}
?>
Now call the function like this
<?php
$notes_set = find_notes_by_id($userRow['id'],$connection);
foreach($notes_set as $note){
echo $note['content'];
}
?>
You have to iterate over.
Problem is with this code
$row = mysqli_fetch_assoc($result);
return $row;
Change that to
$x = array();
while( $row = mysqli_fetch_assoc($result))
{
$x[] = $row;
}
return $x;
Save data into an array. Use it through foreach or for loop.
$content = [];
while($row = mysqli_fetch_assoc($result)){
$content[] = $row['content'];
}
return $content;
Need to change the function like this
function find_notes_by_id($user_id) {
global $connection;
$safe_user_id = mysqli_real_escape_string($connection, $user_id);
$query = 'SELECT content ';
$query .= 'FROM notes ';
$query .= 'WHERE user_id = '.$safe_user_id;
$result = mysqli_query($connection, $query);
//mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 6 [type] => 0 )
confirm_query($result);
$row = array();
while($result1 = mysqli_fetch_assoc($result)){
//Array ( [content] => First! ) = it only shows the very first element
$row[] = $result1;
}
return $row;
}
I'm trying to create an associative array from sql results for json_encode.
here's my code:
$timelineQuery = "SELECT * FROM timeline_table";
$contentQuery = "SELECT * FROM content_table";
$picQuery = "SELECT * FROM pic_table";
$sql = mysql_query($timelineQuery) or die(mysql_error());
$sql2 = mysql_query($contentQuery) or die(mysql_error());
$sql3 = mysql_query($picQuery) or die(mysql_error());
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
echo stripslashes(json_encode($mainArray));
If I json_encode my $mainArray as it is, the returned json has the syntax I'm looking for, but I've not been able to fill the array without adding it to the end of my array.
{"timeline":{"content":{"pictures":[]}}}
first:
while($row = mysql_fetch_assoc($sql)) {
$timelineArray[] = $row;
}
while($row2 = mysql_fetch_assoc($sql2)) {
$contentArray[] = $row2;
}
while($row3 = mysql_fetch_assoc($sql3)) {
$picArray[] = $row3;
}
then:
$mainArray = array(
'timeline' => $timelineArray = array(
'content' => $contentArray = array(
'pictures' => $picArray = array(),
),
),
);
echo stripslashes(json_encode($mainArray));
you defined your array with empty arrays and didn't renew it's states.
I have this piece of code:
Tipo_Id = mysql_real_escape_string($_REQUEST["tipo"]);
$Sql = "SELECT DISTINCT(tabveiculos.Marca_Id), tabmarcas.Marca_Nome
FROM tabmarcas, tabveiculos
WHERE tabmarcas.Tipo_Id = '$Tipo_Id'
AND tabmarcas.Marca_Id = tabveiculos.Marca_Id
ORDER BY tabmarcas.Marca_Nome Asc";
$Query = mysql_query($Sql,$Conn) or die(mysql_error($Conn));
$marcas = array();
while ($Rs = mysql_fetch_array($Query)) {
$marcas[] = array(
$Rs['Marca_Id'] =>
$Rs['Marca_Nome']
);
}
echo ( json_encode($marcas) );
this returns a result like this:
[{"2":"Chevrolet"},{"7":"Citro"},{"4":"Fiat"},{"3":"Ford"},{"6":"Peugeot"},{"1":"Volkswagen"}]
so how i can change to returns like this:
{"2":"Chevrolet","7":"Citro","4":"Fiat","3":"Ford","6":"Peugeot","1":"Volkswagen"}
You're currently creating a new array for each key value pair, hence, ending up with a multidimensional array. Do the following instead.
while ($Rs = mysql_fetch_array($Query)) {
$marcas[ $Rs['Marca_Id'] ] = $Rs['Marca_Nome'];
}