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();
?>
Related
I need help with some code. I want to select data from mySQL to a graph on my web page.
The data must be from the current logged in user, and when I select data to a card it works fine, but when I select it to a graph the graph disappears.
I'm using this code for the cards, and it works fine:
$sql = "SELECT energyexpenditure FROM energy4project WHERE user_id = '{$_SESSION["user_id"]}' ORDER BY time_stamp DESC LIMIT 1;";
This is the code for my current graph that don't show data based on logged in user:
<?php
header('Content-Type: application/json');
$host = "localhost";
$user = "`blabla";
$pwd = "blabla";
$db = "blabla";
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT energyexpenditure, time_stamp FROM energy4project ORDER BY time_stamp DESC LIMIT 7;";
$result = $conn->query($sql);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
mysqli_close($conn);
echo json_encode($data);
?>
When I implement the code from the cards in the graph code it doesn't work.
Why does the SELECT WHERE user = '{$_SESSION["user_id"]} not work in the graphs?
If I understood good your Mysql query return an empty result. Try to modify your code as follows:
if(!$result = $conn->query($sql)) {
echo "query error.";
die();
}
$data = array();
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
$data[] = $row;
}
/* free result set */
$result->free();
/* close connection */
$conn->close();
//uncomment the below line if you want to check de result of your mysql query because it seems be good.
//var_dump($data); die(); echo "<pre>";
echo json_encode($data);
So if you don't have any mysql error, verify your database name, table name are correctly and if it has data in your table.
Reference: https://www.php.net/manual/en/mysqli-result.fetch-array.php
Regards
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}
The script below seems to stall for no reason during the loops. There are 6700 results to loop through, but it stalls between 375-460 results processed. No errors given or logged.
<?php
/* Example usage of the Amazon Product Advertising API */
include("amazon_api_class.php");
ignore_user_abort(true);
set_time_limit(0);
ini_set('memory_limit','256M');
ini_set("display_errors", 1);
ini_set("track_errors", 1);
ini_set("html_errors", 1);
error_reporting(E_ALL);
// define variables
$username = "xxxxxxx";
$password = "xxxxxxx";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//echo "Connected to MySQL<br>";
//select a database to work with
mysql_select_db("xxxxxxxx",$dbhandle)
or die("Could not select database");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM input ORDER BY mpn");
if (!$result) { // add this check.
die('Invalid query: ' . mysql_error());
}
//clear results table before processing
mysql_query("TRUNCATE TABLE results");
mysql_close($dbhandle);
//loop
while($row = mysql_fetch_array($result)) {
$mfg = $row['mfg'];
$mpn = $row['mpn'];
$keyword = $mfg." ".$mpn;
$obj = new AmazonProductAPI();
try{
$data = $obj->getItemByKeyword($keyword);
$asin = $data->Items->Item->ASIN;
$weight = $data->Items->Item->ItemAttributes->PackageDimensions->Weight;
$height = $data->Items->Item->ItemAttributes->PackageDimensions->Height;
$length = $data->Items->Item->ItemAttributes->PackageDimensions->Length;
$width = $data->Items->Item->ItemAttributes->PackageDimensions->Width;
$manufacturer = $data->Items->Item->ItemAttributes->Manufacturer;
$brand = $data->Items->Item->ItemAttributes->Brand;
$partnumber = $data->Items->Item->ItemAttributes->MPN;
$title = $data->Items->Item->ItemAttributes->Title;
$upc = $data->Items->Item->ItemAttributes->UPC;
$ean = $data->Items->Item->ItemAttributes->EAN;
$pricenew = $data->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice;
$priceused = $data->Items->Item->OfferSummary->LowestUsedPrice->FormattedPrice;
$description = $data->Items->Item->ItemAttributes->Feature;
$title = $data->Items->Item->ItemAttributes->Title;
echo ' processing '.$counter++;
//connection to the database
$dbhandle1 = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
mysql_select_db("xxxxxxxx",$dbhandle1)
or die("Could not select db");
//execute the SQL query and return records
mysql_query('INSERT INTO `results`(`mpn`, `mfg`, `brand`, `asin`, `ean`, `upc`, `description`, `low_price_new`, `low_price_used`, `length`, `width`, `height`, `net_weight`, `gross_weight`, `shipped_weight`, `title`) VALUES ("'.$partnumber.'","'.$manufacturer.'","'.$brand.'","'.$asin.'","'.$ean.'","'.$upc.'","'.$description.'","'.$pricenew.'","'.$priceused.'","'.$length.'","'.$width.'","'.$height.'","'.$weight.'","'.$weight.'","'.$weight.'","'.$title.'")');
mysql_error();
mysql_close($dbhandle1);
//unset variables
unset($asin);
unset($weight);
unset($height);
unset($length);
unset($width);
unset($manufacturer);
unset($brand);
unset($partnumber);
unset($packagequantity);
unset($title);
unset($upc);
unset($data);
unset($keyword);
//flush
flush();
//force garbage collection
gc_enable();
gc_collect_cycles();
usleep(50000);
}
catch(Exception $e)
{
//echo $e->getMessage();
}
//print_r($result);
}
echo "<br><h3>Job Completed</h3><br><br><h1><a href='csv_amz.php'>Download Results As CSV File</a></h1><br><br><h1><a href='index.php'>Upload New File</a></h1>";
?>
My primary concern is to get this script to run through the entire list. When testing with 50-100 results, works without any problem.
As a secondary question, within the loop I have an echo with a counter. I would like to get that to display on screen in real time, instead of all at once when script finishes.
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;
}