Forum Moderators: open

Message Too Old, No Replies

Error In SQL syntax

         

jbearnolimits

10:46 pm on Sep 12, 2022 (gmt 0)

Top Contributors Of The Month



Trying to get information out of the database for just the row that matches the id sent via the link. The link ends in: ProfileTest.php/?id=14. The id number depends on the profile. But I'm having trouble figuring out what error I have in the profiletest.php. Anyone mind lending an extra pair of eyes to see what is needed?

I am getting the error: Error: SELECT * FROM `Contacts` WHERE id =
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Below is the code:

<?php
$servername = "SERVERNAME";
$username = "USERNAME";
$password = "PASSWORD";
$dbname = "DBNAME";

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

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

$id = isset($_Get['id']) ? $_GET['id'] : '';


$sql = "SELECT * FROM `Contacts` WHERE id = $id";

if ($conn->query($sql) === TRUE) {
echo "Here is the information";
echo "<h2>YOUR INPUT:</h2>";
echo "$FirstName<br />$LastName<br />$Phone<br />$Email<br />$HomeAddress<br />$HomeCity<br />$HomeState<br />$HomeZip";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

topr8

8:40 pm on Sep 13, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$sql = "SELECT * FROM `Contacts` WHERE id = ".$id;

topr8

8:43 pm on Sep 13, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



a good thing to do if you get an error is, echo the variable $sql to see if it is what you expect or not. (kill the page after the echo so it just shows the $sql string)

jbearnolimits

9:28 pm on Sep 13, 2022 (gmt 0)

Top Contributors Of The Month



Thanks. I managed to figure it out. I did something similar to what you suggested to determine the error.

Dimitri

9:41 pm on Sep 13, 2022 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member Top Contributors Of The Month



$id = isset($_GET['id']) ? $_GET['id'] : '';

$id will always be empty, if you test $_Get instead of $_GET...

...and if $id is empty, you must not run the SQL query, and the remain of the code...

...you must also check if $id is a positive integer, before running the SQL command...

...and in fact, you should "prepare" the SQL statement to avoid arbitrary code injection/execution...

... remember, that anyone can modify the URL, and put anything in the list of parameters...