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.
Related
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;
I have a database that stores a website's news articles. Each row contains a time, title, author, and a content field. Javascript handles the information passed from php and displays it via togglable buttons. For some reason even though I see the data in Mysql Workbench some content fields are returning null. Why would this be?
Here is my code..
var json = <?php
$servername = "sfxworks.net"; //Currently pulls from my webserver. Pass sql credentials or write a php file that I can include that wont show on github.
$username = "foo";
$password = "bar";
$dbname = "foodbarmmmmmmmmm";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$rows = array();
$sql = "SELECT title, author, date, content FROM News";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
echo "0 results";
}
$conn->close();
print json_encode($rows);
?>;
For some reason, after php processes this with error reporting on, I just get null values at random. In the same places, but random.
There are some values in the table with interesting apostrophes..
After removing [ ’ ] from the string and replacing it with [ ' ] the value is no longer null.
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();
?>
Ok so for some reason when I try and get values from a cell in my table with type TEXT it returns nothing, even thought there is text in the cell. It might be because there are new line characters in the text. In fact I'm certain that's the reason cause the only time things aren't return from the table is when there are newlines in it.
Here is the code where I get the data from my db:
function getRecord($cmo_name,$username,$password){
$i = 0;
$servername = "localhost";
$db = "my_db";
$return_array[] = "";
$conn = new mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `my_table` WHERE `Name` = '".$name."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
foreach($row as $value)
array_push($return_array, $value);}
}
$conn->close();
return $return_array;
}
The above code returns nothing for the TEXT column that includes the newlines.
Help please!!!
Wrap your query result in PHP's TRIM function to strip the newline and returns out:
http://php.net/manual/en/function.trim.php
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;
}