mysql_fetch_array problem - php

i am trying to do a guestbook in php but i am having some problems with mysql_fetch_array function. I don't understand why. I try to debug by putting
die("Error ".mysql_error()) but nothing prints out. I guarantee that all my variables are correctly initialized.
Here is my code :
<?php
$nbmessagesPP = 10;
mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.......
if(isset($_GET['page'])){
$page = $_GET['page'];
} else {
$page = 1;
}
$first_msg = ($page - 1) * $nb_of_Page;
$query = 'Select * from livredor ORDER BY id DESC LIMIT '.$first_msg.', '.$nbmessagesPP;
$rep = mysql_query($query) or exit("Error in query".mysql_error());
$v = true;
while($v){
$v = ($data = mysql_fetch_array($rep) or die ("Error fetching the data : ".mysql_error()));
echo "<p>id -> ".$data['id']."</p>";
echo "<p>pseudo ->".$data['pseudo']."</p>";
echo "<p>messages ->".$data['message']."</p>";
echo "<hr/>";
}
mysql_close();
?>
Can someone help me ;)

Your code doesn't deal with errors or the last row correctly. When $v is false, it still goes on to print some data. It would be better rewritten as:
while (($data = mysql_fetch_array($rep))) {
echo
...
}
That forces the evaluation of the fetch before moving on to the printing.

The problem is that you're trying to access elements of the result that don't exist. mysql_fetch_array returns a regular array, with integer indices. What you want is mysql_fetch_assoc, which returns an associative array.
Edit: You also have the problem Chris describes, not dealing with the last row correctly.

Generally, if you're receiving an error saying "supplied argument is not a valid MySQL result resource" it means that your MySQL query has failed, therefor not returning a valid result resource.
Try to echo out $query before sending it through mysql_query(), then try placing the echo'd query into phpMyAdmin and see if it returns any results.

Ok i have found the problem.
The problem was that in another page i had a mysql_connection and in that page i was creating a new one.
I just catch the return value of mysql_connect function and then close it with mysql_close function at the end. Like this :
<?php
$link = mysql_connect(HOST, USER,PASSWORD) or die( "Unable to connect to database");
mysql_select_db(DBNAME) or die ("Unable to select database!");
.....
while($data = mysql_fetch_array($rep)) {//i do something here}
mysql_close($link);
?>
Thanks for your answers folks :)

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!

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

Empty MySQL query result not working as expected?

I am using the following script to check a code, so when the user enters the survey code they get the survey that is associated with that code. The part that fetches the survey is working as its supposed to, but I cant seem to get the error message to come up for some reason. If I enter a wrong code or no code all on the form this posts from, all I get is a blank page.
<?php
$con = mysql_connect("myhost","myuser","mypassword;
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Select mysql db
mysql_select_db("mydb", $con);
$questionaireID = $_POST['questionaireID'];
$result = mysql_query("SELECT * FROM itsnb_questionaire WHERE questionaireID='$questionaireID'") or die(mysql_error());
while($row = mysql_fetch_array($result)) {
if (empty($row['questionaireID'])) {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
} else {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
}
}
?>
It will never get there, because if the resultset is empty, it'll skip the while loop.
Try this, instead, limiting to 1 record (which is what you expect) and using an if...else instead of your while (while is only required when multiple results are expected):
$sql = "SELECT *
FROM itsnb_questionaire
WHERE questionaireID = '{$questionaireID}'
LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if ($row = mysql_fetch_array($result)) {
$url = $row['questionaireurl'];
header('Location: '.$url.'');
} else {
echo '<h2>Sorry I cant find a quiz with that code, please recheck your code.</h2>';
}
If number of returned rows is zero than you haven't found your result therefore you can display apropriate error message
try
if (mysql_num_rows($result)<1){
//error
}

php/sql error - mysql_fetch_assoc()

I'm receiving the following error:
mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource..
and I can't figure out what is going on. Here is my code. I did create a database with a table named notes. Also, the database connection is working correctly. Any idea on what is going on?
$query = mysql_query("SELECT * FROM notes ORDER BY id DESC");
mysql_fetch_assoc($query)
Thanks
var_dump($query);
echo mysql_error();
Did mysql_query fail and return FALSE? As the documentation explains:
For SELECT, SHOW, DESCRIBE, EXPLAIN
and other statements returning
resultset, mysql_query() returns a
resource on success, or FALSE on
error.
FALSE would not be a valid resource.
On the PHP page, it gives you a perfect example of how to use it and do error checking...
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
How about you go and implement the entire way making sure rows are returned, and its a valid resource, and if result is truthy?
You should always debug and never assume something executed rightfully.
In the future please read through the entire page of the function on php.net, in this case it's http://php.net/manual/en/function.mysql-fetch-assoc.php

php mysql connection does not show results why

this is driving me crazy why aren't the results showing???
function runSQL($rsql) {
$connect = mysql_connect('localhost','xxx','xxx') or die ("Error: could not connect to database");
$db = mysql_select_db('xxx');
$result = mysql_query($rsql) or die ("Error in query: $query. " . mysql_error());
return $result;
mysql_close($connect);
}
$rsql = "SELECT * FROM subscriptions WHERE subscriptionID = 6 ";
runSQL($rsql);
$row = mysql_fetch_array($result);
echo $row['subscription'];
mysql_free_result($result);
You don't process your result ...
You call your function (runSQL) to execute the query and it returns the resultset, but you don't catch the resultset to work with it.
Use $result = runSQL($rsql); instead of runSQL($rsql);.
Also note that mysql_close($connect); is never called in your code, it's unreachable as the return occurs first.
If you close the connection before doing mysql_fetch_(assoc|array|etc) on it, those functions will likely fail. The connection should not be closed until you're done interacting with the database, including reading the data.

Categories