PHP MySQL cannot go to line 0

Recently I started to learn webdevelopment, and for the first project we have to make a very simple registration function. now I'm somewhere, but suddenly I started getting this error.

Cannot go to row 0 at MySQL 4 result index.

This is the code where I get the error.

$conn = mysql_connect($servername, $username, $password, $database) or die("!Server");

if(!$conn){
    die("Connection error: " . mysql_error());
}else{
    echo "connection made";
}

$select_db= mysql_select_db($database, $conn);

if(!$select_db){
    die("Database selection failed:: " . mysql_error());
}else{
    echo "database selected";
}

$login_user = $_GET['username'];
$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";
$result = mysql_query($select_password);

if(!$result){
    die("Could not fetch the data " . mysql_error());
}

$password = mysql_result($result, 0);

echo $password;

I know that there are other posts asking the same question, but none of them are very helpful.

I hope someone can help me.

Thanks for reading:)

+4
source share
4 answers

It is possible that this line:

password = mysql_result($result, 0);

It is not possible to get strings if this does not match anything, so you get an error.

Try instead:

if( $password = mysql_fetch_assoc($result) ) {
    echo $password['password'];
} else {
    echo 'no match';
}

See if that helps.

mysql_ * PDO mysqli.

+4

PDO mysql _.... , -, , mysql... .
PDO

, servername, database, username password. PDO :

$con = new PDO("mysql:host=$servername;dbname=$database", $username, $password);

$_GET, filter_input, . :

$login_user = filter_input(INPUT_GET,'username');

:

$result_query = $con->query("SELECT `password` FROM `members` WHERE `username` = '$login_user'");
$result = $result_query->fetch(PDO::FETCH_ASSOC);

$result , :

echo $result['password']; 
+3

Thanks for the help :) from these answers I got everything I needed, and now I will also switch to PDO for the final version, although I am going to stay with MySQL now, since I have to turn it on Monday.

Thanks a lot:)

0
source

Change this:

$select_password = "SELECT `password` FROM `members` WHERE `username` = '$login_user'";

In it:

$select_password = "SELECT password FROM members WHERE username = '$login_user'";
-1
source

Source: https://habr.com/ru/post/1606759/


All Articles