1

I have a database called $addressdb. I want to search through a table on that database with a result the user inputted ($usersName). My mistake is probably really stupid. I am new with mySQL.

<?php

//IF THE LOGIN is submitted...
if ($_POST['Login']){
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "addressdb";
    $usersName = $_POST['users'];

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";
$result = mysqli_query($conn, $sql);

...

My line of error is

$sql = "SELECT userID, userName FROM users WHERE userName =$usersName";

More specifically the variable call.

LifeofBob
  • 37
  • 6

3 Answers3

1

Best approach is :

$sql = "SELECT userID, userName FROM users WHERE userName ='".mysqli_real_escape_string($conn, $usersName)."'";

Here it is not so applicable since you are passing the plain text. But when taking data from html page you should use this way.

Sanjay Kumar N S
  • 4,653
  • 4
  • 23
  • 38
  • 1
    This is a great approach. I haven't tried this yet but by the looks of it, it looks for much better than messing around with single quotes and double-quotes. – KingKong BigBong May 20 '20 at 00:02
0

Try something like this :

$sql = "SELECT userID, userName FROM users WHERE userName = '".$usersName."'";
Thomas Rollet
  • 1,573
  • 4
  • 19
  • 33
0

You need to use quotes around your $userName.

$sql = "SELECT userID, userName FROM users WHERE userName = '$usersName'";

But to be clear, you should escape your user input at least with mysqli_real_escape_string($conn, $userName);

KiwiJuicer
  • 1,952
  • 14
  • 28