简体   繁体   中英

How can I get the id of the record with the email, mysql

I have a test MySQL with a field which is unique as e-mailadres. Now I want to check before adding a record if the email already exists. I have the following code

<?php
$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxx";
$dbname = "xxxxxxx";
$servername = "localhost";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

//test met voorbeeld
$emailtest="adres@me.com ";

$sql = "SELECT * FROM salonkeuze WHERE emailadres='$emailtest' ";
$data = mysqli_query($connect, $sql);
$row = mysqli_fetch_assoc($data);
$id = $row['voorkeur_id'];
Echo $id;
?>

When I use an email address which is in de table. I don't get any output. What do I wrong?

Here $emailtest="adres@me.com "; you can extra space after com , try to remove it -> $emailtest="adres@me.com";

Firstly, you use wrong variable in this line:

$data = mysqli_query($connect, $sql);

Correct:

$data = mysqli_query($conn, $sql);

And it's optional, but it will be good, if you use trim() function for your $email . Because if your data comes from inputs and if $email have spaces, you can't show correct results:

$emailtest = "adres@me.com ";
$emailtest = trim($emailtest);
$sql = "SELECT * FROM salonkeuze WHERE emailadres='$emailtest' ";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM