PHP mysqli_fetch_array gets a general Fatal Error - php

I have to use a php function to manage some data from a db, but i get a Fatal Error on the line where I call mysqli_fetch_array().
$request = "SELECT Post.* FROM Post WHERE IdUseFk = '".$user_idPk."';";
$result = mysqli_query($CONN, $request)
or die ("<font color='red'>Error: ".mysqli_error($CONN)."</font>");
$num = mysqli_num_rows($result);
if ($num == 0) {echo "NOTHING TO DO HERE";}
else
{
for ($i=1; $i<=$num; $i++)
{
$row = mysqli_fetch_array($result, MYSQLI_ASSOC); //<<-- ERROR ON THIS LINE
/*...Some other code...*/
}
}
I get this: Fatal error: in C:\xampp\htdocs\Work\load_data.php on line 137
Any suggestion?
EDIT: PROBLEM SOLVED
I can't believe it. For some reason the 'space' chars I put before and after the '=' char in $row = mysqli_fetch_array()
weren't real spaces but another special char that is blank in most editors but php read as part of the function name. I was able to see it thanks to the editor in cpanel. Now it works

Try using a while loop, and you also had an error in your SQL syntax.
$request = "SELECT Post.* FROM Post WHERE IdUseFk = '$user_idPk'";
$result = mysqli_query($CONN, $request)
or die ("<font color='red'>Error: ".mysqli_error($CONN)."</font>");
$num = mysqli_num_rows($result);
if ($num == 0) {
echo "NOTHING TO DO HERE";
} else {
while($row = mysqli_fetch_array($result) {
/*...Some other code...*/
}
}

Related

JSON returns [null,null] in my app

I want to send database records with a PHPH file via json to my app I am making with IntelXDK. Because I can't use PHP code with the Intel XDK, I needed to use JSON. I want to show the two records 'quote' and 'author' from my 'quotes' table on my screen. Someone helped me to this code but it just returns [null,null]instead of the two records I need.. I tried debugging but I am new to PHP so I can'get it to work.. Anyone who can help or sees an error in this code? Thanks!
PS: Yes I now there are already multiple questions asked on this subject by other people. I have read them all but none of them solves my question..
<?php
if(isset($_GET["get_rows"]))
{
//checks the format client wants
if($_GET["get_rows"] == "json")
{
$link = mysqli_connect("localhost", "xxxxx", "xxxxx", "xxxx");
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
header("HTTP/1.0 500 Internal Server Error");
exit();
}
$query = "SELECT quote, author FROM quotes WHERE id = " . date('d');
$jsonData = array();
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
$row = $result->fetch_assoc($result);
// Create a new array and assign the column values to it
// You can either turn an associative array or basic array
$ret= array();
$ret[] = $row['quote'];
$ret[] = $row['author'];
//encode to JSON format
echo json_encode($ret);
}
else {
echo json_encode($ret);
}
/* close connection */
mysqli_close($link);
}
else
{
header("HTTP/1.0 404 Not Found");
}
}
else
{
header("HTTP/1.0 404 Not Found");
}
?>
You have a bug in fetch_assoc() function call - remove $result parameter. If you had error reporting enabling, you should see:
Warning: mysqli_result::fetch_assoc() expects exactly 0 parameters, 1 given
Just change it to:
$row = $result->fetch_assoc();
In javascript to parse this response, just do this:
var obj = JSON.parse(xmlhttp.responseText);
document.getElementById("quote").innerHTML = obj[0];
document.getElementById("author").innerHTML = obj[1];
I think your problem is with fetch_assoc()
Try to use that :
$row = mysqli_fetch_assoc($result);
instead of
$row = $result->fetch_assoc($result);
It's works for me with your example
change this
$row = $result->fetch_assoc($result);
to
$row = $result->fetch_assoc();
Just change it to:
$row = $result->fetch_assoc();
Updated:
response = JSON.parse(xmlhttp.responseText);
you can now access them independently as:
reponse.quote and response.author

If search returns nothing give error

I have a search form on my website, and I want it to return an error if the user searches for something that does not exist in my database
<?php
$search = $_POST['search' ];
$numrows = mysql_num_rows ($result );
if($numrows != 0) echo "No results";
?>
This is the code that my search form is using, however the echo"no results" shows on the homepage above all of the results, but does not display when there are no results from the search.
I'm a beginner to PHP, so I am completely unsure why this is happening.
If you need my full code, it is below:
http://pastebin.com/xjxwhfDT
wouldn't it be
if($numrows == 0) echo "No results";
if nothing is found ?
your $numrows = mysql_num_rows ($result ); shouldn't be at the place it actually is.
You should do something like :
$count = count($result);
if($count > 0)
{
while ($row =mysql_fetch_object ($result)) {
// do your stuff
}
}
else
{
echo 'no results';
}
also, what is the point of $search = $_POST['search' ]; in your while loop? You don't seem to use it at all.
Firstly, given the code. I would ask if $result contains a query result?
ie.
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
Secondly, mysql_num_rows() returns number of rows or FALSE. So, double check if $results is a valid result set from a valid query.
Hope this helps.
move your if before the while and it works
Now
while ($row =mysql_fetch_object ($result)) {
[...]
$numrows = mysql_num_rows ($result );
if($numrows != 0)
[...]
Correct
$numrows = mysql_num_rows ($result );
if($numrows == 0){ echo 'no result'; die();}
while ($row =mysql_fetch_object ($result))
[...]
Because if result is empty while loop is not executed.
You can use:-
$numrows = mysql_num_rows ($result );
if($numrows > 0){
while ($row =mysql_fetch_object ($result)) {
//- Main Content -
echo '<div class="wrapper">';
?>
<?php
//--------- GET THE POST HTML VARIABLES. PUT INTO PHP VARIABLES -----------------------------
$search = $_POST['search' ];
}
// write your whlie loop code here
}else{
echo "No results";
}
mysql_num_rows Retrieves the number of rows from a result set. Check number of row greater then 0 or not

Error while running php code

i'm making a small PHP application that uses some data to check whether it matches the records of the database or not(a prototype of a login process), but it gives me a (extra junk data error) and when commenting the header line to check the error it gives me that fatal error:
Fatal error: Maximum execution time of 30 seconds exceeded in C:\wamp\www\hh\login.php on line 22
The Code:
<?php
header("Content-type: text/xml");
$host = "localhost";
$user = "muhammed";
$pass = "";
$database = "test";
$linkID = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $linkID) or die("Could not find database.");
$query = "SELECT * FROM info";
$resultID = mysql_query($query, $linkID) or die("Data not found.");
$name = "tahany";
$age = 90;
while(true){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
break;
}else{
$res = "failed to login";
}
}
}
echo $res;
?>
You need to optimize your code, There is no need of extra for loop.
while($row=mysql_fetch_assoc($resultID)){
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
}else{
$res = "failed to login";
}
}
NOTE: mysql_* functions are deprecated move on mysqli_* functions asap.
You getting fatal error because of infinite loop you are putting break in inner loop but outer loop is infinite.
You can (and should) remove the while (true) statement from the code. It is not needed. This is what's causing your timeout. The break statement only breaks the inner for-loop and not the outer while loop.
Now, a fix for the while loop could be something like this:
$break_loop = false;
while (!$break_loop ) {
// Keep your existing code as-is.
for (...) {
if (...) {
...
} else {
...
}
}
// Always break the loop, whether or not the log-in was successful.
// We need to stop the while-loop anyhow.
//
// When the log-in was successful, we jumped out of the for-loop much
// sooner.
$break_loop = true;
}
So we use a temporary variable to keep the loop running until the variable is set to true. This happens when we jump out of the for-loop when the log-in is successful, or when all attempts failed.
But again, the while-loop is not needed because your for-loop handles it already.
it is not good to use this code but it is useful
break 2;
http://php.net/manual/en/control-structures.break.php
If you need to increase the time out of PHP Script. Do this
<?php
set_time_limit(0);
Actual problem lies here in your while loop.
Your while loop is running in a infinite condition. Try changing it like . Always remember while(true) runs infinitely.
$i=0;
while($i==0){
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
if ($row['Name'] == $name && $row['age'] == $age){
$res = "login success";
break;
}else{
$res = "failed to login";
}
}
$i=1; // Changing the flag to 1 , so while condition fails
}

Returning a variable that has to be updated from a function, not returning?

There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}

php string error

i am experiencing some weird behaviour here.
i am using the following code to reference the facebook api.
$query = "SELECT msg, user_id, comment_time FROM comments WHERE aid = '$aid' ORDER BY comment_time DESC";
$result = mysql_query($query) or die("ERROR: $query.".mysql_error());
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_object($result)){
$uidval = $row->user_id;
$posterInfo = $facebook->api_client->users_getInfo($uidval, array('name', 'pic_square_with_logo', 'profile_url'));
$nameuser = $posterInfo[0]['name']; //this is line 50
$pic = $posterInfo[0]['pic_square_with_logo'];
$profile_url = $posterInfo[0]['profile_url'];
echo '<img src="'.$pic.'" />';
echo ''.$nameuser.'';
echo '<br>';
echo $row->comment_time;
echo '<br>';
echo $row->msg;
}
}
it gives me this error:
Fatal error: Cannot use string offset as an array in /home/amitver/public_html/roadies/comments.php on line 50
but surprisingly i am using the exact same code successfully at the top of my page. why this weird behaviour. this is the code at the top of page:
//connect to fB
$uid = $user_id;
$userInfo = $facebook->api_client->users_getInfo($user_id, array('name', 'pic_square'));
$nameuser = $userInfo[0]['name'];
$pic = $userInfo[0]['pic_square'];
I think that sometimes theusers_getInfo is returning an array, while other times it is returning a string. Probably it only returns a simple string if only one result is available.
Try this:
$nameuser = ($posterInfo[0]) ? $posterInfo[0]['name'] : $posterInfo['name'];
this will happen if $posterInfo is actually an empty string ('').
can you var_dump($posterInfo) in the loop and check what it's doing...

Categories