MikeIsMad
MikeIsMad

Reputation: 33

Cannot echo result from mysql

All I need is to produce a row. I've looked at all the samples and I cannot for the life of me get the right information. Hence help is required please.

Connection to DB in the usual way. Here is my code for the query.

$sql = "SELECT * FROM table WHERE `u_password` = $pword AND `user` = $uname LIMIT 1";
$result = mysqli_query($mdb, $sql);
$row = mysqli_fetch_assoc($result);
//Then I try to retrieve say the user name....
echo $row['seeking'];

I've got a count in there and it produces a result of 1. The error I get is 'Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result'

Help would be appreciated.

Upvotes: 0

Views: 41

Answers (2)

RiggsFolly
RiggsFolly

Reputation: 94642

The error

Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result

Almost always means that the query failed for some reason, thus $result = mysqli_query returns FALSE rather than a mysql_result object so anything that then tries to use $result as an object will not work for obvious reasons.

The issue with your query is that text column data must be wrapped in quotes like this

$sql = "SELECT * 
        FROM table 
        WHERE `u_password` = '$pword' AND `user` = '$uname' LIMIT 1";

Your script is at risk of SQL Injection Attack Have a look at what happened to Little Bobby Tables Even if you are escaping inputs, its not safe!

You should use parameterized queries to avoid this.

$sql = "SELECT * 
        FROM table 
        WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql);
// its also a good idea to check the staus of a prepare 
// and show the error if it failed, at least while testing
if ( $stmt === FALSE ) {
    echo mysqli_error($mdb);
    exit;
}
$stmt->bind_param('ss', $pword, $uname );
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
echo $row['seeking'];

Upvotes: 2

apokryfos
apokryfos

Reputation: 40653

You need to use prepared statements (in actuality you could get it to work by quoting your strings but prepared statements are much better). Like so:

$sql = "SELECT * FROM table WHERE `u_password` = ? AND `user` = ? LIMIT 1";
$stmt = mysqli_prepare($mdb, $sql); 
$stmt->bind_param("ss",$pword,$uname);

if ($stmt->execute()) {
    $result = $stmt->get_result();
    $row = mysqli_fetch_assoc($result);
     //Then I try to retrieve say the user name....
    echo $row['seeking'];
} else { /* something went wrong */ }

Upvotes: 0

Related Questions