Convert data from db to JSON using php - php

I have already seen many questions but nothing has helped.
I want to convert my data from database (MySQL) to JSON using PHP. This is my PHP code:
init.php
<?php
$db_name = "webappdb";
$mysql_user = "root";
$mysql_pass = "root";
$server_name = "localhost";
$charset= "utf8";
$con = mysqli_connect($charset, $server_name, $mysql_user, $mysql_pass, $db_name);
?>
listViewBooks.php
<?php
include("init.php");
header('Content-Type: application/json');
// get all items from user_info_book table
$sql = mysqli_query("SELECT * FROM `user_info_book`");
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$output[] = $row;
}
echo json_encode($output);
echo json_last_error();
mysqli_close($con);
?>
The error is 0, so it's nothing.

There are a bunch of problems in your code. For starters, you have this:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
$res = mysqli_query($con,$sql);
$sql is a mysqli_result object on success or boolean false on failure. Here, it's false because you didn't pass the database link ($con). See the docs. You shouldn't, don't need to, and can't store the result of mysqli_query in a variable ($sql) and then pass that variable in another call to mysqli_query. Just do:
$sql = "SELECT * FROM `user_info_book`";
$res = mysqli_query($con, $sql);
Also, you initialize one array, then add to another:
$result = array();
while($row = mysqli_fetch_array($res)){
$output[] = $row;
}
Perhaps you mean to do $output = array();?
You would benefit from using an IDE like PHPStorm.

So you execute a query and assign the result to $sql:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
But then you query again and use the $sql result as if it were a string:
$res = mysqli_query($con,$sql);
Probably more what you were thinking:
$sql = "SELECT * FROM `user_info_book`";
$res = mysqli_query($con,$sql);
You should use error reporting when developing:
error_reporting(E_ALL);
ini_set('display_errors', '1');

You code is bad:
$sql = mysqli_query("SELECT * FROM `user_info_book`");
^---missing DB handle
^---query result handle
So $sql becomes boolean false for failure, because you didn't call the query function correctly.
You then blindly use this boolean false as if it was a query string:
$res = mysqli_query($con,$sql);
^---boolean false, due to previous errors
So basically, you assumed your code was perfect, and could never ever possibly have any problems, so failed to add any error handling. Since you have no error handling, you utterly ignored the errors that DID occur.
Never EVER assume success - this code is a perfect example of WHY. Your sql is syntactically perfect, yet it failed because you didn't call the query function properly.
Always assume failure, check for failure, and treat success as a pleasant surprise.

You initialize an array called $result but try to use an array with the $output identifier which has not been initialized, PHP will not auto-initialize an array variable for you. That is where one error comes from.
The second error I noticed is:
mysqli_query("SQL")
You forgot to pass in the database connection resource as it should be:
mysqli(db_connection, sql_query)
Fix those then if you need more assistance, comment below.
Have a good day.

Related

PHP mySQL Simple Echo from SELECT

I am trying to create a simple echo from a SELECT from DB.
It echos blank always.
Here is the code:
<?php
$username = "xxxx";
$password = "xxxx";
$hostname = "xxxx";
$conn = mysqli_connect($hostname, $username, $password, "xxxx");
if(! $conn ) {
die('Could not connect: ' . mysqli_error());
}
$user = $_GET['user'];
$pass = $_GET['pass'];
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$retval = mysqli_query($conn, $sql);
echo($retval);
mysqli_close($conn);
?>
It would be greatly appreciated if someone could help and tell me what I am doing incorrectly :)
If it worked, you didn't get ID back, but a "mysqli_result" object.
Try print_r($retval) to see what you really got.
If it's a mysqli_result object, you need another step to get the data.
while ($row = $retval->fetch_assoc()) {
echo $row['id'];
}
According to the manual:
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return TRUE.
Moreover, please note that a query that runs but returns zero results is still considered a "successful query" since the query did run in the database and an empty result set is a legitimate response. This means the query will still return a mysqli_result object.
As I understood the code so far, if you want to echo results returned you could use mysqli_fetch_array(), so your code would become:
/* numeric array */
$row = mysqli_fetch_array($retval, MYSQLI_NUM);
And you can echo it as:
echo $row[0];
or
/* associative array */
$row = mysqli_fetch_array($retval, MYSQLI_ASSOC);
And then you could echo as:
echo $row['id'];
Furthermore, you can use mysqli_fetch_assoc() to loop over your results or for fetching single row instance purposes, an example is:
while ($row = $result->fetch_assoc()) {
echo $row['id'];
}
Returns an associative array of strings representing the fetched row in the result set, where each key in the array represents the name of one of the result set's columns or NULL if there are no more rows in the resultset.
And if you want to check if your query has found any rows, you can use mysqli_num_rows
Which works as the following:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($retval);
Do you know if you are connected to the database or not? You could try changing a value to see if the error comes up or not.
If thats not the issue this should work better:
$host = 'xxxx';
$user = 'xxxx';
$pass = 'xxxx';
$db = 'xxxx';
$mysqli = new mysqli($host,$user,$pass,$db) or die($mysqli->error);
$sql = "SELECT id FROM 'users' WHERE user='$user' AND pass='$pass'";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()) {
$whateverString = $row['cakes'];
}
echo $whateverString;
Now lets say that you had a value in the mysql row called cakes that is equals to 5 then it will fetch that specific string from the row if the user and pass is correct.
So the value above will output "5" if the mysql value 'cakes' is 5.
Thanks for your answers, people!
I ended up with this:
$q=mysqli_query($con,"SELECT id FROM `users` WHERE user='$username' and pass='$password'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if(json_encode($data)== '[]'){
echo 'error';
}else {
echo json_encode($data);
}
?>

Connection is made to the database with php script but no values are returned

I have a successful connection to the database through this php script but it is not returning any values even though it is connected. I am checking for the results on my web browser and it just returns a blank screen. I have used the same script (different queries) to access two other tables in the database and they are both working fine. Here is my code:
<?php
$username = "xx";
$password = "xxx";
$host = "xxxxx";
$database="xxxxx";
$server = mysql_connect($host, $username, $password);
$connection = mysql_select_db($database, $server);
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
if ( ! $query ) {
echo mysql_error();
die;
}
$data = array();
for ($x = 0; $x < mysql_num_rows($query); $x++) {
$data[] = mysql_fetch_assoc($query);
}
echo json_encode($data);
mysql_close($server);
?>
It is probably some silly mistake that I have over looked but I have been stuck on it for longer than I should! thanks in advance for any feedback
Tried you code locally on some data and it returns everything ok.
I needed to change the select to match my data
So I am 95% sure the problem is in your query / db settings.
I would first check if your columns in database is really called AUTHOR and 'In_order' with the exact capital letters.
MySql names can be case sensitive depending on your db server settings, and this could be the problem
Sidenote: if you can research mysqli and pdo for connecting to DB instead of mysql that is deprecated.
Try this:
$myquery = "SELECT `AUTHOR`, `In_order` from `authors`";
$query = mysql_query($myquery);
$num = mysql_num_rows($query);
var_dump($query);
var_dump($num);
echo mysql_error();
and tell us what it all says.
Edit: okay, so it's 231 rows in your table, as the var_dump($num) says. Now let's try and get them at last, but in a slightly more efficient way:
while ($row = mysql_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
I have a feeling that your "for" loop and mysql_fetch_assoc() inside is what plays tricks with you, because both of them use different internal counters.

PHP undefined index error in communicating with android

I am retrieving data from a database in android so created a php file as below.
<?php
$db_host = "localhost";
$db_uid = "root";
$db_pass = "";
$db_name = "abc";
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$sql = "SELECT * FROM people WHERE birthyear > '". $_POST["birthyear"]."'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
Now when i run it in the browser as localhost/script.php
error is thrown and the output is displayed as below
Notice: Undefined index: birthyear in C:\xampp\htdocs\jasonscript.php on line 14
[{"id":"1","name":"m","sex":"1","birthyear":"1989"},{"id":"2","name":"a","sex":"1","birthyear":"1986"},{"id":"3","name":"b","sex":"0","birthyear":"1986"}]
Please tell me how to correct my code.
$output[]=array("key"=>$row['field_name'],"key1"=>$row['field_name2']);
store array like this
You are directly inserting $_POST["birthyear"] in your query which makes you vulnerable to SQL injection. Stop doing it right now!
That is also why you get the error. When you directly call the script in your browser, that will be with a GET request and there wont be any POST variables available. So your $_POST array wont have a key for birthyear and thus it warns you about it.
You should start with something like
<?php
$by = isset($_POST["birthyear"]) ? $_POST["birthyear"] : "";
if (empty($by)) {
echo 'Invalid birthyear';
exit;
}
//SANITIZE YOUR BIRTHYEAR HERE
//in this case, probaly check for a integer between 1900 and 2100 or something.
//Although just an int could be enough to prevent injection
if (!is_int($by)) {
echo 'You failed to provide a valid year';
exit;
}
$sql = "SELECT * FROM people WHERE birthyear > '". $by."'";
//execute the code
?>
Although the above code is safe, you should check out bound parameters like used in mysqli prepared statements or PDO
you probably failed to send the values trough post properly.
try print_r($_POST); to see what you are actually sending
you still get all results because every year is > ''

Mysql Query, comparing values and assigning to PHP variables

I have done a fair bit of research into what i want to do, although i haven't found anything. I am not too sure if i am looking for the right thing :( I am also a little bit new to PHP and MySQL syntax, so please be kind.
I wish to perform the following in this order:
Connect to a database (DONE)
Query for a specific string (I think im done)
From here is gets a bit fuzzy :(
If a match is found for the variable, copy the whole row (I need other variables).
Assign the values from the SQL query to a PHP variables.
From there i will be right to carry on.
I have established the connection to the database with the following:
function connect() {
$dbname = 'database';
$dbuser = 'username';
$dbpass = 'password';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
}
And then calling the function connect();
I then wish to query the database for a particular value, for the sake of this argument i will use a static value. This is what i have:
mysql_select_db(DATABASENAME) or die( "Unable to select database");
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'";
$result=mysql_query($query);
From here i am not too sure how to compare the query result to see if it is a match (something along the lines of mysql rows?).
If there is a match, then i would like to obtain the entire row, and assign each value to a php variable.
I am not asking for you to do it for me, simply i kick in the right direction should be fine!
Hope it explains it enough :)
Thanks for your kind guidance
Ok. You will want to keep the connection to the mysql database somewhere. A common use is $conn.
So you would have
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
Then, either from the URL or Post, or just some variables you have sitting in your php file, you can query the database by putting the variables in the query itself. Also, here you can use $conn so that you have one place to connect to the database, in an include for example, and you won't have to make all of the connection string in each place you need to connect to the DB.
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%" . $varToCompare . "%'";
$result=mysql_query($query,$conn);
Above you are using a like. You may want to just look at doing .. Where column=$var.
Then you can use php to spin through the results into an array (for queries where would get multiple rows).
Where the hell you learned how to use MySQL in PHP ? The mysql_* functions are more then 10 years old and not maintained anymore. Community has already begun to work on deprecating them.
You should be using PDO or MySQLi for that.
// connection to database
$db = new PDO('mysql:host=localhost;dbname=datadump_pwmgr;charset=UTF-8',
'datadump_pwmgr',
'kzddim05xrgl');
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// setting up prepared statement for the query
$statement = $db->prepare('SELECT * FROM table WHERE column LIKE :value');
$statement->bindParam(':value', $some_variable, PDO::PARAM_STR, 127);
// executing query and fetching first result
if ( $statement->execute())
{
$data = $statement->fetch(PDO::FETCH_OBJ);
var_dump( $data );
}
This should give you something like what you needed. Though, I would recommend to try this tutorial. And learning more about prepared statements could be useful too.
Also , if you are working with objects, then it is possible to create a single DB connection object , and pass it to multiple other classes to use it:
$pdo = new PDO('sqlite::memory:');
$a = new Foo( $pdo );
$b = new Bar( $pdo, 'something');
This way you pass both objects the same database connection, and you do not need to reinitialize it.
I think you're looking for something like this:
$count = mysql_num_rows($result);
//if there is more then 1 record retrieved from the database
if($count > 0)
{
//Do what ever you want to do here, which I think you want to be
while ($row = mysql_fetch_assoc($result))
{
echo $row["Columnname1"];
echo $row["Columnname2"];
echo $row["Columnname3"];
}
}
else
{
echo "There are no matches for this specific value";
}
You can get the queried data by rows as an associated array using mysql_fetch_array():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_array($data)) !== false)
{
echo "row = $row, name1 = " . $result["name1"] . ", name2 = " . $result["name2"];
$row ++;
}
... or as an objects using mysql_fetch_object():
$row = 0;
$data = mysql_query("SELECT name1,name2 FROM ....");
while(($result = mysql_fetch_object($data)) !== false)
{
echo "row = $row, name1 = $result->name1, name2 = $result->name2";
$row ++;
}
I'm not too sure of what you want, but I can see one probable bug here: you're using LIKE in a way which means =: in order to have LIKE to behave like a like, you need some joker chars :
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE 'VAULE'" // This will return all rows where column='VAUL'
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'" // This will return all rows where column='%VAUL%' // This will return any row containing 'VAUL' in column
"SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE'" // This will return all rows where column='%VAUL' // this will return all rows ending by VAUL. I guess you get it now :)
An to retrieve the actual results:
$query = "SELECT * FROM `TABLE` WHERE `COLUMN` LIKE '%VAULE%'";
$result=mysql_query($query);
while (false !== ($row = mysql_fetch_assoc($result))) {
//here $row is an array containing all the data from your mysql row
}
Try to write the database connection in another page no need to use function and include that page in where ever you need.
ex: require_once 'dbConnect.php';
dbConnect.php consists:
<?php
$dbname = 'datadump_pwmgr';
$dbuser = 'datadump_pwmgr';
$dbpass = 'kzddim05xrgl';
$dbhost = 'localhost';
mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to connect to database");
?>

Why am I returning empty records when querying in mysql with php?

I created the following script to query a table and return the first 30 results. The query returns 30 results, but they do not have any text or information. Why would this be?
The table stores Vietnamese characters. The database is mysql4.
Here's the page: http://saomaidanang.com/recentposts.php
Here's the code:
<?php
header( 'Content-Type: text/html; charset=utf-8' );
//CONNECTION INFO
$dbms = 'mysql';
$dbhost = 'xxxxx';
$dbname = 'xxxxxxx';
$dbuser = 'xxxxxxx';
$dbpasswd = 'xxxxxxxxxxxx';
$conn = mysql_connect($dbhost, $dbuser, $dbpasswd ) or die('Error connecting to mysql');
mysql_select_db($dbname , $conn);
//QUERY
$result = mysql_query("SET NAMES utf8");
$cmd = 'SELECT * FROM `phpbb_posts_text` ORDER BY `phpbb_posts_text`.`post_subject` DESC LIMIT 0, 30 ';
$result = mysql_query($cmd);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html dir="ltr">
<head>
<title>recent posts</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<p>
<?php
//DISPLAY
while ($myrow = mysql_fetch_row($result))
{
echo 'post subject:';
echo(utf8_encode($myrow ['post_subject']));
echo 'post text:';
echo(utf8_encode($myrow ['post_text']));
}
?>
</p>
</body>
Try using mysql_fetch_assoc() instead of mysql_fetch_row()
The former returns an array with each
result column stored in an array
offset, starting at offset 0.
The later returns an associative
array of strings where the column as
used as keys.
And in your program you are using the result as an associative array:
$myrow ['post_subject']
or you could try mysql_fetch_object() and access the data as $myrow->post_subject. If you feel the data is still not displayed, then do a print_r($myrow) to the the output. This way you will know for sure if the data has been returned.
If you use mysql_fetch_row(), you're going to need to access your data through numbered keys (ie $row[0], $row[1], etc). mysql_fetch_object() is the norm today in most applications to fetching rows as mentioned by Shamly.
I'm not a big fan of using PHP's provided functions to do daily coding. Instead, considering writing (or downloading) a class or a few functions to help do the job for you, like:
function my_query($query){
$return = array(); // stuff to return
$result = mysql_query($query);
while($row = mysql_fetch_object($result)){
array_push($return, $row);
}
return $return;
}
So then all you have to do is this in your script:
// connect to db, fill in the appropriate arguments...
$link = mysql_connect(...);
// selecting database
mysql_select_db($dbname, $link);
// do the query
$rows = my_query(...);
foreach($rows as $row){
print_r($row); // see what's in there...
}
By using the my_query() function, you save yourself a few steps. This is also particularly useful doing nested queries within loops. What's easier to read?
// assume database is already connected
$result = mysql_query('SELECT user_id FROM table');
while($row = mysql_fetch_object($result)){
$result_2 = mysql_query('SELECT * FROM other_table WHERE user_id = '.$row->user_id);
while($row_2 = mysql_fetch_object($result_2)){
// do stuff with both rows
// potential for lots of confusion and mysql errors
}
}
or this...
// assume database is already connected
$user_ids = my_query('SELECT user_id FROM table');
foreach($user_ids as $x){
$more_data = my_query('SELECT * FROM other_table WHERE user_id = '.$x->user_id);
foreach($more_data as $y){
// do stuff
}
}
Anyway, probably a much longer answered than you expected, but I hope it gives you an idea of how to go about things :) If you have time, install Wordpress and learn how to use its built in $wpdb object. You will gain a wealth of knowledge of how databases are used in real life applications and you'll be able to make your own database class to suit your needs.
DISCLAIMER: I just wrote all the above code for this post without testing for syntax errors. I apologize if there are any.
use:
while ($myrow = mysql_fetch_array($result))
{ ... }
it will work

Categories