:Store SQL Data in a php array - 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;
}

Related

Json total result mysql

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;

Some table values returning null?

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.

creating new db rows from data in array?

Hey guys im trying to pass some data from an (oracle) fetch_array to a variable array and then use that array data to check if the data exists on a mysql db and create any rows that dont currently exist.. this is what i have so far.
the problem is its only checks/creates 1 entry of the array and doesn't check/created the entire array data. i think i would need to use a for loop to process all the array data concurrently
<?php
$conn = oci_connect('asdsdfsf');
$req_number = array();
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, " SELECT WR.REQST_NO
FROM DEE_PRD.WORK_REQST WR
WHERE WR.WORK_REQST_STATUS_CD = 'PLAN' AND WR.DEPT_CD ='ISNG'
");
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
// Use the uppercase column names for the associative array indices
$req_number[]= $row['REQST_NO'];
}
oci_free_statement($stid);
oci_close($conn);
//MYSQL
//Connection Variables
//connect to MYSQL
$con = mysqli_connect($servername,$username,$password,$dbname);
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
// lets check if this site already exists in DB
$result = mysqli_query($con,"
SELECT EXISTS(SELECT 1 FROM wr_info WHERE REQST_NO = '$req_number') AS mycheck;
");
while($row = mysqli_fetch_array($result))
{
if ($row['mycheck'] == "0") // IF site doesnt exists lets add it to the MYSQL DB
{
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
if (mysqli_query($con, $sql)) {
$created = $req_number." Site Created Successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}else{ // if site is there lets get some variables if they are present...
$result = mysqli_query($con,"
SELECT *
FROM wr_info
WHERE REQST_NO = '$req_number[0]'
");
while($row = mysqli_fetch_array($result))
{
$do some stuff
}
}
}
mysqli_close($con);
?>
You create an array:
$req_number = array();
And loop over records to assign values to the array:
while (($row = oci_fetch_array($stid, OCI_BOTH+OCI_RETURN_NULLS)) != false) {
$req_number[]= $row['REQST_NO'];
}
But then never loop over that array. Instead, you're only referencing the first record in the array:
$sql = "INSERT INTO wr_info (REQST_NO)VALUES ('$req_number[0]')";
// etc.
(Note: There are a couple of places where you directly reference the array itself ($req_number) instead of the element in the array ($req_number[0]), which is likely an error. You'll want to correct those. Also: You should be using query parameters and prepared statements. Getting used to building SQL code from concatenating values like that is a SQL injection vulnerability waiting to happen.)
Instead of just referencing the first value in the array, loop over the array. Something like this:
for($i = 0; $i < count($req_number); $i++) {
// The code which uses $req_number, but
// referencing each value: $req_number[$i]
}

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();
?>

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