Passing mysql_query to JSON file does not work - php

I have a small code that should convert a query to my mysql database into a json file, but it does not return anything.
I have seen this example in many places but it does not work for me
Of course I checked before the query contains rows
I appreciate the help
<?php
if (!$enlace = mysql_connect('X.X.X.X', 'xxxx', 'xxxx') or !mysql_select_db('xxxx', $enlace)) {
echo 'No pudo conectarse a mysql';
exit;
}
$sql = 'SELECT * FROM `Tabla`';
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json[]=$row;
}
echo json_encode($json);
?>

The reason for not getting anything is because you are overwriting the array variable,
also note that you need to use mysqli since mysql_ is deprecated.
Change this line:
$resultado = mysql_query($sql, $enlace);
$json = array();
while($row=mysql_fetch_assoc($resultado)){
$json=$row;
}
to:
$resultado = mysqli_query($sql, $enlace);
$json = array();
while($row=mysqli_fetch_assoc($resultado)){
$json[]=$row;
}

Fist of all use mysqli instead of mysql it is deprecated since PHP 5.5.0.
And then add the row to the array instead of overwriting it.
$json[] = $row;
for test add this line in the loop
$json = [];
while($row = mysql_fetch_assoc($resultado)){
$json[] = $row;
print_r($row);
}
If you get no output the query is not giving you any results

You may try converting to array to be sure.
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
}
and yes simple debugging is important just use var_dump() to identify the issue
var_dump(['socket:', $resultado]); $i=0;
while($row=mysql_fetch_assoc($resultado)){
$json[]=(array)$row;
var_dump([$i++, $row]);
}
exit();
And of course you should not use deprecated functions but i assume this is a learning environment or just an old working system

Related

Foreach loop does not work correctly (PHP)

here is my code
$query = mysql_query("SELECT * FROM accommodation_vacancies WHERE accommodation_id = '$accom'");
$results = mysql_fetch_array($query);
if($query === FALSE) {
die(mysql_error());
} else {
print_r($results);
foreach ($results as $result) {
echo $result['start_date']; echo "<br/>";
}
}
And here is my output
By using the print_r commant i can see that The variable $results works properly,the query works properly also, i guess that i have mistakes on the foreach loop.
Thank you.
You are only fetching a single result. Use a while loop instead.
while ($result = mysql_fetch_array($query)) {
Side note: As stated in the comments, the mysql_* functions are deprecated. You should NOT learn how to use mysql using these deprecated methods. They will be removed from PHP in some future version and your code will stop working then. If you learn it, use mysqli_* or PDO.

MySQL time-exceeded error

I am currently working on an AJAX testing platform. I am experiencing stupid errors in PHP programming. Here is my code. I get the error: Maximum execution time of 30 seconds exceeded.
<?php
$resultFromJson;
$databaseConnection = mysql_connect("localhost", "root", "password");
if($databaseConnection)mysql_select_db("fastdata", $databaseConnection);
else echo mysql_error($databaseConnection);
if(isset($_GET['command'])){
switch($_GET['command']){
case "loadPeople":
{
$sqlCommandString = "SELECT * FROM `people` LIMIT 0 , 30";
$people = array();
$index = 0;
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString))){
$people[$index] = $row;
$index++;
}
echo json_encode( $people );
}
break;
}
}
if(!isset($_GET['command']))echo json_encode( "Error#001" );
?>
What can I do to solve this error? What actually causes the error?
P.S. I am currently testing my PHP script directly in the browser with main.php?command=loadPeople as URL.
Execute the query, then loop through the results; don't try to re-execute the query in every iteration of the while
$resultset = mysql_query($sqlCommandString);
while ($row = mysql_fetch_assoc($resultset)) {
As you're clearly just learning the basics, I'd suggest that you learn to use MySQLi or PDO rather than the deprecated MySQL library... being able to use prepared statements and bind variables doesn't affect this query, but knowing how to use them will become more important later
i haven't written any PHP code in a while so this is a wild guess but in this piece of code:
while($row = mysql_fetch_assoc(mysql_query($sqlCommandString)))
you essentially have a neverending loop because $row will be assigned every time mysql_fetch_assoc(mysql_query($sqlCommandString)) returns a result
you need to save mysql_query($sqlCommandString) into a variable and then mysql_fetch_assoc from that variable in a loop

PHP JSON array from SQLite3

I'm trying convert data from a SQLite3 db to a JSON array by using PHP. I'm getting close, but I can't seem to get it right.
This is the error I'm getting:
PHP Warning: PDOStatement::fetchAll() expects parameter 1 to be long, object given in...
Thanks!
<?php
$db = new PDO('sqlite:example.db');
$result = $db->query('SELECT * FROM test');
$json = array();
$result->setFetchMode(PDO::FETCH_ASSOC);
while ($data = $result->fetchall($result)){
$x = $data['Time'];
$y = $data['Temperature'];
$json[] = array( (int($x)), (int($y)) );
}
?>
Got it working now. Thanks for your help!
<?php
$db = new PDO('sqlite:example.db');
$result = $db->query('SELECT * FROM test');
$datapie = array();
$result->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $result->fetch()) {
extract($row);
$datapie[] = array(floatval($Temperature), $Time);
}
$data = json_encode($datapie);
?>
Change:
$result->fetchall($result)
to:
$result->fetch()
You had two problems: the argument to fetchAll() should be a fetch mode, not a result. And fetchAll() returns all the rows, not one row at a time. If you're calling in a loop you use fetch().
PDO's fetchAll function, doesn't expect the query itself as a param.
Check it's manual here - you can leave it blank, or set the fetch mode:
http://php.net/manual/en/pdostatement.fetchall.php

Retrieve MySQL field using PHP

I need to get a field from a mySQL database using PHP
The problem is that in my mysql panel I use this sql code:
SELECT * FROM TESTS WHERE TEST_ID=1
and I get exactly what I want (I see the row that I want to display)
But if i use this code in PHP:
<?php
$con=mysql_connect("localhost", "root", "psw") or die("\nConnection Failed\n");
mysql_select_db("mydb")or die("\nDB Failed\n");
$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);
echo $result;
mysql_close($con);
?>
all I get is "Resource ID #3"
why??
the $result is a resource which is a link to a result set from mysql. To get the actual data you have to do something like:
$data = mysql_fetch_assoc($result);
print_r($data);
You would need to repeat the mysql_fetch_assoc() call for each row you want to retrieve, until it returns false, indicating there are no more rows, which can be done in a while loop like this:
while ($data = mysql_fetch_assoc($result)) {
print_r($data);
}
Watch out :
This extension is deprecated as of PHP 5.5.0, and will be removed in
the future. Instead, the MySQLi or PDO_MySQL extension should be used.
you can use mysql_fetch_assoc
$result=mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo $row["userid"]; // sample column
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_fetch_assoc example
You have received a MySQL resource instead of the resultset you want. You've only received a pointer to the result.
You have to use functions like mysql_fetch_object, mysql_fetch_assoc, mysql_fetch_row etc to get the wanted resultset. Please check the manual here:
http://php.net/manual/en/book.mysql.php
Try to fetch result in any variable and print that It will work.
Like this :
<?php
$con=mysql_connect("localhost", "root", "psw") or die("\nConnection Failed\n");
mysql_select_db("mydb")or die("\nDB Failed\n");
$query = "SELECT * FROM TESTS WHERE TEST_ID=1";
$result=mysql_query($query);
$row = mysql_fetch_array($result)
print_r($row);
mysql_close($con);
?>
Hope this will help you... :)

Can we send result of mysql query as return value of function using php?

I m creating function that process query and pass it's return result back. so I used following code:
function test(){
$query = "select * from mytable where id=123";
$data = mysql_query($query) or die(mysql_error());
return $data;
}
$info = test();
is it possible and can i use $info to get values as $info[0],$info[1]..
take a look at mysql_fetch_array function.
This function lets you iterate a query result which is a resource and turn each row into an array.Therefore you should use a while loop to get all rows in a resource;
You're missing one vital part, returning the result of mysql_query() just returns a result pointer not the dataset. You should add mysql_fetch_array, mysql_fetch_assoc or mysql_fetch_row:
function test(){
$query = "select * from mytable where id=123 LIMIT 1";
$data = mysql_query($query) or die(mysql_error());
$result = mysql_fetch_row($data);
return $result;
}
$info = test();
now you can use $info[0], $info[1]. When using mysql_fetch_assoc you could use $info['fieldname'].
I also added LIMIT 1, since you're sending a long an ID, this probably is unique and after 1 result there is most likely nothing else to be returned.
You can do that, however it is better in my experience to keep the database stuff encapsulated, so you don't expose MySQL resources outside of the database context that then further need mysql_fetch_assoc() and the like on them.
I would use PDO there, and return the results of fetchAll(PDO::FETCH_ASSOC). That way, $info has the data it needs without needing to run further database functions on.
<?php
$link = mysql_connect('localhost', 'USERNAME', 'PASSWORD');
mysql_select_db('DB NAME', $link);
function test()
{
$result = mysql_query("select * from wp_options");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row;
}
return $data;
}
echo "<pre>";
print_r(test());
echo "</pre>";
mysql_close($link);
?>

Categories