PHP JSON array from SQLite3 - php

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

Related

Passing mysql_query to JSON file does not work

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

PHP/Sqlite3: Fatal error: Call to undefined function sqlite_num_rows()

I am getting this error when I call the function sqlite_num_rows. It must not be dependency issue since other Sqlite functions are working. I'm able to open connection and get data from DB.
4 Years late but i had the same issue so here is my Solution for anyone that has the same problem
//$db is the database handle
$result = $db->query("SELECT * FROM table_name");
$rows = 0; //set row counter to 0
while($row = $result->fetchArray()) {
$rows += 1; //+1 to the counter per row in result
}
Relative to info on php.net
neither of "sqlite_num_rows($result)" and "$result->numRows()" is not
working on SQLite3 ! you should use this way:
<?php
$db = new SQLite3('databasename.db');
$result = $db->query("SELECT * FROM users");
$rows = count ($result);
echo "Number of rows: $rows";
Click me

Using Arrays in MySQLi And PHP

Following is a typical OOP way to Connect and Retrive data from MySQL database using MySQLi and PHP.
Now I am a little bit confused on using the pure PHP arrays at this example:
Can some one please let me know if the $result is array or not? I mean in
$result = $mysqli_coonect->query($sql);
if so how come we didn't use the array() function or [] to create it?!
same thing happening with $row at:
$row = $result->fetch_assoc()
I am asking this because in order to load $row; to $results[] at $results[] = $row; we declared the $results as an array explicitly before the while() how come we are not doing this for other or vice versa?!
<?php
$mysqli_coonect = new mysqli($host_name, $user_name, $pass_word, $database_name, $port);
$sql = "SELECT * FROM books WHERE id <= 10";
$result = $mysqli_coonect->query($sql);
if (($result) && ($result->num_rows > 0))
{
$results = array();
while ($row = $result->fetch_assoc())
{
$results[] = $row;
}
$result->free();
}
$mysqli_coonect->close();
Always refer to the PHP documentation. It's great and you can easily find what you want.
http://php.net/manual/en/mysqli.query.php states that a query will return mixed in this case meaning either false if the query failed or mysqli_result object of the query was successful.
Getting down to business
$result = $mysqli->query($query) returns a mysqli_result object. This means that $result is now an object.
We then call the method fetch_assoc from our newly created $result (mysqli_result) object and store the results of the method in the variable $row (which if the method is successful will be an array). If you look at what fetch_assoc returns (http://php.net/manual/en/mysqli-result.fetch-assoc.php) you see that it returns an array.
We loop through our newly created $row array.

Loading MySQL data into a PHP array

I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?
Code:
//Get active listing IDs
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());
if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};
Thanks,
Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.
while($row = mysql_fetch_array($active)) {
// Your code here
}
Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.
In PDO it's rather straight forward:
$rows = $conn->query($active)->fetchAll();
See PDO::queryDocs and PDOStatement::fetchAllDocs.
With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.
Code for mysqli
$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
$rows = $result->fetch_all();
}
with PDO it's nearly the same
$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
$rows = $result->fetchAll();
}

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