Json total result mysql - php

I am having difficulty displaying the total number of the result of the mysql query using json.
I tried this rule but it only returns like this:
{"Total1": "10"}
I need to return it with the []:
[{"Total1": "10"}]
Follows the php code:
<?php
include 'DatabaseConfig.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT revenda, quantidade FROM app_venda";
$result = $conn->query($sql);
$total1 = mysql_num_rows($result);
if ($result->num_rows > 0) {
// output data of each row
$row[total1] = $total1;
$json = json_encode($row);
} else {
echo "0 results";
}
echo $json;
$conn->close();
?>

Then you need to add another array around the data
$total1 = 10;
echo json_encode( array(array('Total1' => $total1)) );
Result
[{"Total1":10}]
Or using your code with a correction in the array definition. Notice $row['total1'] = 10; uses quotes around the array name to stop this error
Notice: Use of undefined constant total1 - assumed 'total1'
$row['total1'] = 10;
echo json_encode( array( $row ) );
Can I suggest in furutre you test code with these lines added to the top of all your scripts
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This will force any mysqli_ errors to
generate an Exception that you can see on the browser and other errors will also be visible on your browser.

$total1 = mysql_num_rows($result);
$row = array();
if ($result->num_rows > 0) {
// output data of each row
$row[][total1] = $total1;
$json = json_encode($row);
} else {
echo "0 results";
}
echo $json;

Related

Error is Trying to get property 'id' of non-object, but seems object has

I am using PHP for 1st time.
I am just trying to fetch data from database. Here is my code -
try{
///try to connect with database
$conn=new PDO("mysql:host=localhost:3306;dbname=try", "root", "abcdef12");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo "error";
}
$mysqlcode="SELECT * FROM users";
$ret=$conn->query($mysqlcode);
foreach($ret as $ret1)
print $ret1->id;
in the browser,
showing this error:
Notice: Trying to get property 'id' of non-object in /opt/lampp/htdocs/secAsite/verifylogin.php on line 44
In the users table, I have 4 data.
In here, why $ret seems non object. I can't find anything wrong. How to fetch data. Or debug the object.
I have checked your code. Everything is fine. Just do this.
foreach($ret as $ret1)
print $ret1['id'];
You are not getting data because you are not fetching it..
you have to fetch the data before print it
updated code
$mysqlcode = "SELECT * FROM users";
$ret = $conn->query($mysqlcode);
if ($ret->num_rows > 0) {
// output data of each row
while($row = $ret->fetch_assoc()) {
echo "id: " . $ret["id"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
that'll work fine.
Before trying to use Object Oriented PHP, is much easier to understand Procedural. Take a look at the code below.
First, connect to database:
<?php
//Store log in info into variables
$servername = 'localhost';
$serveruser = 'youruser';
$serverpassword = 'yourpassword';
$serverdatabase = 'yourdatabase';
// Create connection
$conn = mysqli_connect( $servername, $serveruser, $serverpassword, $serverdatabase );
if ( !$conn ) {echo "Connection Fail" . mysqli_connect_error();}
//else {echo "Connected to database $serverdatabase";}
?>
Then, call the information from your database and your table and store it into an associative array $data
$sql = "SELECT * FROM `table`";
$result = mysqli_query($conn, $sql);
$data = mysqli_fetch_all($result, MYSQLI_ASOCC);
mysqli_free_result($result);
Now you can use the array to print the results with print_r
echo '<pre>'; print_r($data); echo '</pre>';}
Now you are ready to use foreach depending on your table columns,for example if you have ID column then
<?php foreach ($data as $value){
echo $value['id]."<br>";
} ?>
It will print out all the IDs. Hope this helps.

Why do i get more results from my mysql query in php then what i ask for?

I am getting return values that do not exist in my current database. Even if i change my query the return array stays the same but missing values. How can this be what did i do wrong?
My MYSQL server version is 10.0.22 and this server gives me the correct result.
So the issue must be in PHP.
My code:
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Result:
array(1) {
[1]=> array(9) {
["UID"]=> string(1) "1"
["CreationTimestamp"]=> NULL
["UpdateTimestamp"]=> NULL
["ProcessState"]=> NULL
}
}
Solution:
I have found this code somewhere in my program. The program used the same name ass mine. This function turns the MYSQL result into a array. This happens between the result view and my script. This was done to make the result readable.
parent::processUpdatedAfter($date);
Function:
public function processUpdatedAfter($date)
{
$result = parent::processUpdatedAfter($date);
$array = Array();
if($result != false)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$array[$row["UID"]]["UID"] = $row["UID"];
$array[$row["UID"]]["CreationTimestamp"] = $row["CreationTimestamp"];
$array[$row["UID"]]["UpdateTimestamp"] = $row["UpdateTimestamp"];
$array[$row["UID"]]["ProcessState"] = $row["ProcessState"];
}
return $array;
}
return false;
}
I edited this and my script works fine now thanks for all the help.
Note that, var_dump($result); will only return the resource not data.
You need to mysql_fetch_* for getting records.
Example with MYSQLi Object Oriented:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > \"[given time]\"";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['UID'];
}
}
else
{
echo "No record found";
}
$conn->close();
?>
Side Note: i suggest you to use mysqli_* or PDO because mysql_* is deprecated and closed in PHP 7.
You are var_dumping a database resource handle and not the data you queried
You must use some sort of fetching process to actually retrieve that data generated by your query.
$ts = '2016-09-20 08:56:43';
$select_query = "SELECT process_state.UID
FROM process_state
WHERE process_state.UpdateTimestamp > '$ts'";
$result = mysql_query($select_query, $link_identifier);
// did the query work or is there an error in it
if ( !$result ) {
// query failed, better look at the error message
echo mysql_error($link_identifier);
exit;
}
// test we have some results
echo 'Query Produced ' . mysql_num_rows($result) . '<br>';
// in a while loop if more than one row might be returned
while( $row = mysql_fetch_assoc($result) ) {
echo $row['UID'] . '<br>';
}
However I have to mention Every time you use the mysql_
database extension in new code
a Kitten is strangled somewhere in the world it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions.
Start here
$select_query = "SELECT `UID` FROM `process_state ` WHERE `UpdateTimestamp` > \"[given time]\" ORDER BY UID DESC ";
$result = mysql_query($select_query, $link_identifier);
var_dump($result);
Try this hope it will works

Mysql table using LIMIT, breaks randomly

When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>

:Store SQL Data in a php array

I need to add data from mySQL to an array in a php script. However, the script is set to execute once a day automatically, and the array would vary in size. Is there a way to make a php array that varies in size depending on the amount a data acquired from mySQL?
Update:
So far this is what I have (after removing all the confidential info, of course)
$var1 = array();
$var2 = array();
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else
{
echo "Connected successfully";
}
echo "\r\n";
//select data from
$sql = //SQL File here
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc()) {
$var1 = $row[Row 1];
$var2 = $row[Row 2];
}
?>
Depending on how you grab your info, you can add each line from the MySQL query to an array as you loop through results.
while( $row = mysql_fetch_assoc( $result)){
$new_array[] = $row;
}

Getting sum() of all values in a column of a mySQL database

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) { $miles[] = $row['totalDistance'];
}
Echo $result;I am struggling to get my code to work, I am trying to output the total of all of the values in the 'distance' column of my database.
I get the error notice: "undefined variable: miles"
This is my code:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT sum(distance) AS totalDistance FROM strava";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) { $miles[] = $row['totalDistance'];
}
Echo $result;
}
?>
You don't appear to assign a value to $miles anywhere. Do you perhaps mean to use $result instead?
The construct $miles[] = is a shortcut for appending a new element to an array $miles, but you haven't yet defined $miles, therefore $miles is undefined at that line of the code.

Categories