-3

I am trying to insert a value into my mysql table by using a variable but i can´t get it to work as it takes the variable as an empty variable, what have i done wrong?

<?php
$conn=new mysqli("domain","user","password","database");
if($conn->connect_error)
{
    die("Connection failed: " . $conn->connect_error);
}
$name ="test2";
$email="1234";
$password ="1234";
$sql="INSERT INTO android(name,email,password) values('$name','$email','$password')";

echo $sql;
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} 
else {
echo "Error: " . $sql . "<br>" . $conn->error;
} 

$conn->close();
?>

which gives me the response:

Error: insert into android(name,email,password) values('','','') Duplicate entry '' for key 'PRIMARY'

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Ella
  • 1
  • 2

1 Answers1

0

I believe you are still in the process of learning php MySQL.. My suggestion to you is to stop this tutorial(s) that you are currently using, and start learning prepared statements with mysqli or pdo, and never store passwords in plain text even if you are practicing on your local machine, its better to start learning the correct way of doing thing from the word go..

php have amazing functions to hash and secure your passwords, password_hash() and password_verify()

Your code with mysqli prepared should look like

<?php
$servername = "localhost";
$username = "user";
$password = "password";
$hash = password_hash($password,PASSWORD_DEFAULT);
$dbname = "database";

$name ="test2";
$email="1234";
$password ="1234";
$hash=password_hash($password,PASSWORD_DEFAULT);


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// prepare and bind
$stmt = $conn->prepare("INSERT INTO android (name,email,password) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $hash);
$stmt->execute();

echo "New records created successfully";

$stmt->close();
$conn->close();
?>

Your error is on the duplicate on email that u made a primary key on your table, so therefore you need to check if that email does not exists before you can insert it.

Your proper code should be something like:

<?

$sql = $con->prepare("SELECT email from android WHERE email = ? LIMIT 1");
$sql->bind_param('s', $email);
$sql->execute();

$sql->bind_result($email);
$sql->store_result();
if ($sql->num_rows == 1) //row exists
    {
    if ($sql->fetch()) //contents of the row
        {

        echo $email . "already registered";
    }
} else {
    //email does not exist lets insert

    // prepare and bind
    $sql = $conn->prepare("INSERT INTO android (name,email,password) VALUES (?, ?, ?)");
    $sql->bind_param("sss", $name, $email, $password);


    $sql->execute();

    echo "New records created successfully";

    $sql->close();
    $conn->close();

}
?>
Masivuye Cokile
  • 4,754
  • 3
  • 19
  • 34