-2

I want to select an email from the DB which needs to return the related Account_ID

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "connected accounts details";

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


$sql = "SELECT acc_id FROM users 
WHERE
email = $user_email";

$result = $conn->query($sql);

echo "$result";

$conn->close();

This code returns nothing, just blank. While using the same connection/db data is being inserted in db successfully.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Malik Asif
  • 35
  • 4
  • SELECT acc_id FROM users WHERE email = 'emailhere'; try to run this query in SQL and check you got data or not ? – Developer Dec 12 '20 at 05:51
  • 1
    Learn to use parameters to get values into SQL queries. This will not only solve your problem (missing quotes) but also prevent other funny errors and SQL injections. Have look [here](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – sticky bit Dec 12 '20 at 05:56
  • @Developer means `$sql = "SELECT acc_id FROM users WHERE email = '$user_email'";`. The string literal (inserted `$user_email` value) must be enclosed with single quotes in the query text. – Akina Dec 12 '20 at 06:07
  • $sql = "SELECT `acc_id` FROM `users` WHERE `email` = '$user_email'"; ` use this every table or coloumn – Developer Dec 12 '20 at 06:13
  • @Developer yes tried in sql, its returning the record. – Malik Asif Dec 12 '20 at 06:17
  • Is the `$dbname` and `$user_email` set correct? Try: `$sql = "SELECT acc_id FROM users WHERE email LIKE '%$user_email%'";` – Cyborg Dec 12 '20 at 06:28

2 Answers2

1

Try this code

    // Php Sql Select From DB....
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "connected accounts details";

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

    $sql = "SELECT `acc_id` FROM `users`  WHERE `email` = ?";
    $result->$conn->prepare($sql);
    $result->bind_param('s',$user_email);
    $result->execute();
    $data = $result->get_result();
    // Fetch all
    $data->fetch_all(MYSQLI_ASSOC);
    print_r($data);
    $mysqli -> close();

  // @link http://php.net/manual/en/mysqli-result.fetch-all.php
Developer
  • 466
  • 7
  • 18
-2
$sql = "SELECT acc_id FROM users 
        WHERE
        email LIKE '%$user_email%' ";



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

        $row = $result->fetch_assoc();

        $id = $row['acc_id'];

        echo "$id";

        $conn->close();

Got the wanted Record, trying this way. Thanks everyone answering on this post.

Malik Asif
  • 35
  • 4