PHP: json_encode() doesn't show anything with multidimensional array - php

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.

User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.

Try
echo json_encode($output) ;

It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');

Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable

Related

Selecting * from table returns nothing

I wrote this php script that allows me to fetch all the rows in a table in my MySQL database.
I have put the echo "1", etc. to see whether it gets to the code at the very end. The output proves it does. However, it does not output anything when echoing json_encode($resultsArray), which I can't seem to figure out why.
Code:
// Create connection
$connection = mysqli_connect("localhost", "xxx", "xxx");
// Check connection
if (!$connection) { die("Connection failed: " . mysqli_connect_error()); } else { echo "0"; }
// select database
if (!mysqli_select_db($connection, "myDB")) { die('Unable to connect to database. '. mysqli_connect_error()); } else { echo "1"; }
$sql = "select * from myTable";
$result = mysqli_query($connection, $sql) or die(mysqli_error($connection));;
echo "3";
$resultsArray = array();
while($row = mysqli_fetch_assoc($result)) {
// convert to array
$resultsArray[] = $row;
}
echo "4";
// return array w/ contents
echo json_encode($resultsArray);
echo "5";
Output:
01345
I figured, it is not about the json_encode, because I can also try to echo sth. like $result['id'] inside the while loop and it just won't do anything.
For testing, I went into the database using Terminal. I can do select * from myTable without any issues.
Any idea?
After around 20hrs of debugging, I figured out the issue.
As I stated in my question, the code used to work a few hours before posting this question and then suddenly stopped working. #MichaelBerkowski confirmed that the code is functional.
I remembered that at some point, I altered my columns to have a default value of an empty string - I declared them as follows: columnName VARCHAR(50) NOT NULL DEFAULT ''.
I now found that replicating the table and leaving out the NOT NULL DEFAULT '' part makes json_encode() work again, so apparently there's an issue with that.
Thanks to everybody for trying anyway!

Can't fetch data from database table.... 500 error

I have tried a ton of different versions of this code, from tons of different websites. I am entirely confused why this isn't working. Even copy and pasted code wont work. I am fairly new to PHP and MySQL, but have done a decent amount of HTML, CSS, and JS so I am not super new to code in general, but I am still a beginner
Here is what I have. I am trying to fetch data from a database to compare it to user entered data from the last page (essentially a login thing). I haven't even gotten to the comparison part yet because I can't fetch information, all I am getting is a 500 error code in chrome's debug window. I am completely clueless on this because everything I have read says this should be completely fine.
I'm completely worn out from this, it's been frustrating me to no end. Hopefully someone here can help. For the record, it connects just fine, its the minute I try to use the $sql variable that everything falls apart. I'm doing this on Godaddy hosting, if that means anything.
<?php
$servername = "localhost";
$username = "joemama198";
$pass = "Password";
$dbname = "EmployeeTimesheet";
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
$sql = 'SELECT Name FROM Employee List';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "Name: " . $row["Name"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
There be trouble here:
// Create connection
$conn = mysqli_conect($servername, $username, $pass, $dbname);
// Check connection
if (mysqli_connect_errno) {
echo "Failed to connect to MySQL: " . mysqi_connect_error();
}
There are three problems here:
mysqli_conect() instead of mysqli_connect() (note the double n in connect)
mysqli_connect_errno should be a function: mysqli_connect_errno()
mysqi_connect_error() instead of mysqli_connect_error() (note the l in mysqli)
The reason you're getting a 500 error is that you do not have debugging enabled. Please add the following to the very top of your script:
ini_set('display_errors', 'on');
error_reporting(E_ALL);
That should prevent a not-so-useful 500 error from appearing, and should instead show the actual reason for any other errors.
There might be a problem here:
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
If the query fails, $result will be false and you will get an error on the mysqli_num_rows() call. You should add a check between there:
$result = mysqli_query($conn, $sql);
if (!$result) {
die('Query failed because: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) > 0) {
The name of your database table in your select statement has a space in it. If that is intended try:
$sql = 'SELECT Name FROM `Employee List`';
i think you left blank space in your query.
$sql = 'SELECT Name FROM Employee List';
change to
$sql = "SELECT `Name` FROM `EmployeeList`";

PHP MySQL unable to jump to row 0

I recently started studying webdevelopment and for the first project we have to make a very simple login and registration function. now I got somewhere but suddenly I started getting this error.
Unable to jump to row 0 on MySQL result index 4.
This is the code where I get the error.
$conn = mysql_connect($servername, $username, $password, $database) or die("!Server");
if(!$conn){
die("Connection error: " . mysql_error());
}else{
echo "connection made";
}
$select_db= mysql_select_db($database, $conn);
if(!$select_db){
die("Database selection failed:: " . mysql_error());
}else{
echo "database selected";
}
$login_user = $_GET['username'];
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
$result = mysql_query($select_password);
if(!$result){
die("Could not fetch the data " . mysql_error());
}
$password = mysql_result($result, 0);
echo $password;
I know there are other posts asking the same question but none of them where really helpful.
hope someone is able to help me.
Thanks for reading :)
It is possible that this row:
password = mysql_result($result, 0);
Cannot get rows when it does not match anything which is why you get the error.
Try instead:
if( $password = mysql_fetch_assoc($result) ) {
echo $password['password'];
} else {
echo 'no match';
}
See if that helps.
However, you really should move from mysql_* to PDO or mysqli.
I suggest to work with PDO, instead of mysql_... functions.
Not only because it's newer and object oriented but also because mysql... is deprecated.
So my answer is with PDO
From your code example I assume you have variables of servername, database, username & password. So to connect with PDO will look like this:
$con = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
Then you can take your $_GET parameter using filter_input, which is also more suggested. Simple assignment look like this:
$login_user = filter_input(INPUT_GET,'username');
and then to run & fetch query like this:
$result_query = $con->query("SELECT `password` FROM `members` WHERE `username` = '$login_user'");
$result = $result_query->fetch(PDO::FETCH_ASSOC);
Now $result is an associative array, so to get password just use:
echo $result['password'];
Thanks alot for the help :) out of these answers I got everything I needed and now I am also going to switch to PDO for the final release though I am gonna stay with MySQL for now since I have to turn it in by monday.
Thanks alot :)
Change this:
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
Into this:
$select_password = "SELECT password FROM members WHERE username = '$login_user'";

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

My php script is not using given username/pass/host rather using root#localhost (password: NO)

Got a problem! Though I found almost similar threads but none helped :(
I've written a php script to fetch the number of registered users from my MySQL database. The script is working great in my localhost; it is using the given username,pass and host name which are "root", "root", and "localhost" respectively, but the script is not using the given username/pass/host rather using root#localhost (password: NO) in Live server.
In the Live server I created a MySQL user, set an different password, and hostname there is of course not localhost. I updated the script with my newly created mysql users data. BUT, whenever I run the script, I see that the script is still using "root", "root", and "localhost"!!
take a look at the script:
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
$db = mysql_select_db ("regdb",$conn); //Oops, actually it was written this way in the script. I misstyped it previously. now edited as it is in the script.
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ");
while ($row = mysql_fetch_array($query)):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
-- Some says to change the default username and pass in the config.ini.php file located in phpMyAdmin directory. Would this help?? I didn't try this because either my hosting provider didn't give me privilege to access that directory (because I am using free hosting for testing scripts) or I simply didn't find it :(
Please help....
Foreword: The MySQL extension is marked as deprecated, better use mysqli or PDO
Though you store the connection resource in $conn you're not using it in your call to mysql_query() and you're not checking the return value of mysql_connect(), i.e. if the connection fails for some reason mysql_query() "is free" to establish a new default connection.
<?php
//database connection
$conn = mysql_connect( "mysql.examplehost.com", "myusername", "mypass" );
if ( !$conn ) {
die(mysql_error()); // or a more sophisticated error handling....
}
$db = mysql_select_db ("regdb", $conn);
if ( !$db ) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
//Query to fetch data
$query = mysql_query("SELECT * FROM regd ", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
while ( false!=($row=mysql_fetch_array($query)) ):
$total_regd = $row['total_regd'];
endwhile;
echo $total_regd;
edit: It looks like you're processing only one row.
Either move the echo line into the while-loop or (if you really only want one record) better say so in the sql statement and get rid of the loop, e.g.
// Query to fetch data
// make it "easier" for the MySQL server by limiting the result set to one record
$query = mysql_query("SELECT * FROM regd LIMIT 1", $conn);
if (!$query) {
die(mysql_error($conn)); // or a more sophisticated error handling....
}
// fetch data and output
$row=mysql_fetch_array($query);
if ( !$row ) {
echo 'no record found';
}
else {
echo htmlspecialchars($row['total_regd']);
}
First of all:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('foo', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
What is your mysql_error()? :)

Categories