I know this has been asked like a million times now.
I tried several solutions I found here but still it doesn't work for me.
What i want to do is SELECT Values out of a simple MySQL Table.
The Values are inserted every five minutes by a program I have written.
I catches all mp3 files in a selected folder and inserts its ID3 Tags into the Table tb_song.
These files should then be SELECTED with the PHP Script and an Android App should Play these files with their URL.
The Database and PHP Code works.
If I just echo all selected values it works fine.
But converting and printing out the encoded array just throws an blank screen.
Could it be that JSON Objects are limited to size?
I've got about 500 entries in tb_song.
Here's my code.
<?php
require_once('config.php');
$connection=new mysqli($server,$user,$password,$database);
$songs=array();
$sql=("SELECT Title,Artist,Album FROM tb_song");
$result=$connection->query($sql);
while($row=$result->fetch_assoc())
{
$temp=array();
$temp['Title']=$row['Title'];
$temp['Artist']=$row['Artist'];
$temp['Album']=$row['Album'];
array_push($songs,$temp);
}
json_encode($songs);
echo(json_encode($songs));//just for testing purposes
$connection->close();
?>
You can distil your code down to this. Plus adding some error checking!
<?php
/* add next 2 lines while testing,
especially if you are using a live hosting site
where error reportinf will be turned off
*/
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
// Check connection is good
if ($connection->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();
$sql = 'SELECT Title,Artist,Album FROM tb_song';
$result = $connection->query($sql);
if ( ! $result ) {
echo $connection->error;
exit;
}
while($row=$result->fetch_assoc()) {
$songs[] = $row;
}
$jstring = json_encode($songs);
if ( json_last_error() > 0 ) {
file_put_contents('json-output.txt', json_last_error_msg());
}
echo $jstring;
//add this line for testing
file_put_contents('json-output.txt', $jstring);
exit;
?>
I finally figured it out.
I guess this is not the standard which's happening to all people but anyway.
Before I'll post my code I want to say a few things for people who are running into the same problem:
Make sure you're only passing strings without 'ä','ü' or whatever letter that is not in the english alphabet.
You need to give your JSON Object a Name, otherwise it could cause problems.
<?php
require_once 'config.php';
$connection = new mysqli($server,$user,$password,$database);
if ($connection->connect_error) {
die('Connect Error (' . $connection->connect_errno . ') '
. $connection->connect_error);
}
$songs=array();//Create Array
$sql = 'SELECT * FROM tb_song';
$result = $connection->query($sql);
while($row=$result->fetch_assoc()){
array_push($songs,$row);//Insert $row in $songs
}
echo json_encode(array('Songs'=>$songs));//Giving JSON Object a proper Name and //encode
$connection->close();
?>
Related
I am following the last part of the following video tutorial "How to create a database website with PHP and mySQL 07 - Add in input form" :
https://www.youtube.com/watch?v=MGIG00d1Xzc&list=PLhPyEFL5u-i0zEaDF0IPLYvm8zOKnz70r&index=7
At the end here is my code, for the inserting portion to the database for the new_jokes.php script (everything up to this point of the series I have gotten to work fine so far)
Basically I am getting the seemingly classic "INSERT INTO" not working although all my syntax looks correct. Am I missing something obvious here? I get no errors, just the row isn't added.
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question
$new_joke_answer </h2>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES
(NULL, '$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
include "search_all_jokes.php";
?>
Return to the main page
Here is the db_connect.php code as requested:
<?php
// four variables to connect the database
$host = "localhost";
$username = "root";
$user_pass = "usbw";
$database = "test";
// create a database connection instance
$mysqli = new mysqli($host, $username, $user_pass, $database);
?>
Here is search_all_jokes.php (which has minor error checking):
// if there are any values in the table, select them one at a time
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " .
$mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "SELECT JokeID, Joke_question, Joke_answer FROM Jokes_table";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "JokeID: " . $row["JokeID"]. " - Joke_question: " .
$row["Joke_question"]. " " . $row["Joke_answer"]. "<br>";
}
} else {
echo "0 results";
}
?>
Also here is the table structure screenshot viewed in myPHPAdmin:
I added error capturing into new_jokes.php inspired by this Stack Overflow post:
INSERT INTO SYNTAX ERROR
And get the following error:
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 't jump.' )' at line 1localhost via TCP/IP
Thank you everyone for helping out with this! Syntax can really throw a wrench in everything. I also will read up on prepared statements since that also could have prevented the issue. The ultimate help to this I found the solution to by adding the function referenced here for MySQLi real_escape_string to clean the single quote I had within the answer I was submitting to my joke table:
(Can a kangaroo jump higher than the empire state building? Of course, the empire state building can't jump.)
As shown in the documentation #miken32 linked as a comment here it is says: "But if $val1 or $val2 contains single quotes, that will make your SQL be wrong. So you need to escape it before it is used in sql; that is what mysql_real_escape_string is for. (Although a prepared statement is better.)"
But now the code for this part 7 of the tutorial on you tube I found works and adds it into a row on the database table, then displaying the full new table on the next webpage. I spent a good while shooting in the dark on while the answer ended up being fairly simple. Again special thanks to #miken32 for pointing me the right direction.
Here is my completed code that ended up working to at least achieve the goal of the tutorial:
<?php
include "db_connect.php";
$new_joke_question = $_GET["newjoke"];
$new_joke_answer = $_GET["newanswer"];
$new_joke_question = $mysqli->real_escape_string($new_joke_question);
$new_joke_answer = $mysqli->real_escape_string($new_joke_answer);
// Search the database for the word chicken
echo "<h2>Trying to add a new joke and answer: $new_joke_question $new_joke_answer
</h2>";
if ($mysqli->connect_errno) {
echo "Connection to MySQL failed: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "<br>";
$sql = "INSERT INTO Jokes_table (JokeID, Joke_question, Joke_answer) VALUES (' ',
'$new_joke_question', '$new_joke_answer' )";
$result = $mysqli->query($sql);
if ($mysqli->query($sql) === TRUE) {
echo 'users entry saved successfully';
}
else {
echo 'Error: '. $mysqli->error .'<br>';
}
include "search_all_jokes.php";
?>
Return to the main page
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!
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`";
I am struggling to view some data via PHP. I have a SQL database with Google. I am struggling to extract the data and desperately need some help!
The PHP keeps saying there is 0 records, even though there is a number of records within the 'timing' database and 'events' table.
If anyone has any ideas why this is not working I would be very grateful!
<?php
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully ';
$sql = "SELECT event_id FROM events";
$result = $link->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Event ID</th><th>Event Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["event_id"];
}
echo "</table>";
}
else {
echo "0 results";
}
mysql_close($link);
?>
Ok i think i got it. From PHP.net:
OO syntax only: If a connection fails an object is still returned. To check if the connection failed then use either the mysqli_connect_error() function or the mysqli->connect_error property as in the preceding examples.
This means $link in your code will always be a MySQLi resource, and that it will always cast to true. What you need to do is to check your resource object for errors properly, like this:
if ($link->connect_error)
die('Connect Error: ' . $link->connect_error);
Unless timing is a defined constant, and it looks like that is not the case, being that a string you should wrap it in quotes or double-quotes. A non-defined constant should cast to a string in any case, but since i can't see any other error in your code that might be what is causing your issue. Try changing
$link = new mysqli('IP_ADDRESS:3306','root','PASSWORD',timing);
to
$link = new mysqli('IP_ADDRESS:3306', 'root', 'PASSWORD', 'timing');
Quick question here, i've got a process running that grabs RSS feeds and adds them to a mySQL database.
During this process I'll be using the Readability API to grab the URL content as I go.
Now this works fine on single entries, but as this script can have hundreds of entries, nothing is being inserting into my database.
I'm wondering if it's not getting a chance to finish the process and immediately skipping onto the next entry in the RSS.
Can anyone suggest a way of letting it finish before moving on? Code below:
$db_hostname="localhost";
$db_username="myusername";
$db_password="mypassword";
try
{
/* query the database */
$db = mysql_connect($db_hostname,$db_username,$db_password);
if (!$db)
{
die("Could not connect: " . mysql_error());
}
mysql_select_db("MyDB", $db);
// Get stories that don't have a the readability assigned
$query="select item_id, item_url from tw_articles_parse where story_readability = '' LIMIT 0 , 1";
$result=mysql_query($query);
$num=mysql_numrows($result);
// Close the DB connection
mysql_close();
// Start the loop of source RSS feeds
$i=0;
while ($i < $num) {
$item_url=mysql_result($result,$i,"item_url");
$item_id=mysql_result($result,$i,"item_id");
// Parse the story URL into the Readability API
$url = "https://www.readability.com/api/content/v1/parser?url=$item_url&token=myapikey";
// Get the contents of the JSON returned by the API
$json = file_get_contents($url);
// Decode the JSON
$out = json_decode($json, true);
// Set the content as a variable
$story = mysql_real_escape_string($out['content']);
// Insert into the DB - Adding 0 to story_club_id as default
$item_insert_sql = "UPDATE tw_articles_parse SET story_readability=$story WHERE item_id='" . $item_id . "'";
$insert_item = mysql_query($item_insert_sql, $db);
$i++;
}// end the loop of feeds
} catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
Probably nothing is inserted because you are using UPDATE statement and there are simply no such records with correspoding item_id to be updated?
Try changing UPDATE query to INSERT ... ON DUPLICATE KEY UPDATE
Unfortunately we don't know your database scheme, but something like this should work:
$item_insert_sql = "INSERT INTO tw_articles_parse (story_readability, item_id) VALUES ('$story', $item_id) ON DUPLICATE KEY UPDATE story_readability='$story'";
Maybe you're running out of memory or time? Enable warnings and error reporting:
ini_set("display_errors", 1);
error_reporting(E_ALL);