Google SQL PHP No Data Showing - Connected - php

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');

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`";

Small section of PHP/mysql code dies. Not sure why

I rarely do programming. I only know enough to be dangerous as they say and I simply assemble bits of code to get what I want. My code below seems to die at the $sql query statement. It never returns any data. It should show the 13 records that are present, but it says there is none to return. I'm guessing this is some kind of syntax error?
<?php
$host = 'myipaddress';
$user = 'myuser';
$pass = 'mypass';
$db = 'mydatabase';
$conn = mysql_connect($host, $user, $pass, $db) or die("Can not connect." . mysql_error());
// Create connection
//$conn = mysqli_connect($host, $user, $pass, $db);
// Check connection
if (!$conn) {
die("Connection failed: ");
}
$sql = "SELECT * FROM pages WHERE pid > '5'";
$result = mysql_query($conn, $sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
mysql_close($conn);
?>
Your using the mysql_ API right up until you try to fetch rows here, where you're using mysqli_. That will not work.
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
Your script is at risk for SQL Injection Attacks. Please stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really pretty easy.
EDIT: Your connection (Good Eyes Ralph!) string will not work because mysql_connect() doesn't accept the database as part of the connection. You must use the additional function mysql_select_db() to choose your database.
In addition, it is not necessary to specify the connection link in mysql_query() but if you do it should be the second argument:
$result = mysql_query($sql, $conn);
There is quite a bit wrong with your code.
mysql_connect($host, $user, $pass, $db)
mysql_connect() uses 3 parameters, the 4th doesn't do what you think it does.
http://php.net/manual/en/function.mysql-connect.php
You need to use mysql_select_db() http://php.net/manual/en/function.mysql-select-db.php
Then,
$result = mysql_query($conn, $sql);
The connection comes second in mysql_.
http://php.net/manual/en/function.mysql-query.php
Then you're mixing a MySQLi function mysqli_fetch_assoc which doesn't intermix with the mysql_ library.
Read: Can I mix MySQL APIs in PHP?
So, just use the full MySQLi library
http://php.net/manual/en/book.mysqli.php
or PDO:
http://php.net/manual/en/book.pdo.php
Along with a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
Check for the real errors, should your query fail:
http://php.net/manual/en/function.mysql-error.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
As you can see, I did not provide you with a full rewrite, as I feel that in "Teaching a person how to fish...", will feed them for life, rather than "Throwing them a fish...", and only feed them for a day (wink).
You need to use mysql_fetch_assoc() in place of mysqli_fetch_assoc(), because your previous functions are based on mysql_*, not mysqli_*
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_assoc($result)) {
echo "id: " . $row["pid"]. " - Name: " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}

Newbe, MySQL query skips first entry - no duplicate fetch_array

trying to get my head around this MySQL jibberish, lol - now I do not normally ask for help but on this one I think I do need a shove.
I have searched for the answers to this however the solutions are all based around the askers duplication of the fetch_array command, however I have not done this but still this code skips the first entry.
Can someone point out what I have done here that causes this to skip...?
code:
$link = mysqli_connect('localhost','person','password', 'database'); // connect to database
if (!$link) { die('Could not connect to MySQL: ' . mysqli_connect_error()); } // problem, then die
$sql = "SELECT * FROM id_info_db"; // Query construct
$result = mysqli_query($link, $sql); //query action
while ( $row = mysqli_fetch_array($result) ) { // print out rows
echo "User: " . $row["username"]. " - Password: " . $row["password"]. " " . $row["email"]. "<br>"; }
mysqli_close($link);
For some reason I had a loose /body tag at the end? why I don't know but it generated this result. Now I have deleted it the output is correct.
A remnant that should have been deleted that throws up an unfathomable error. Lol

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

Categories