Anh
Anh

Reputation: 3

PHP MYSQL Couldn't execute query: Unknown column

Please help me to figure out this. The first query would return a message saying that

Couldn't execute query: Unknown column 'ssd23' in 'where clause.

ssd23 is the value the $_POST will get for the pnumber from a html form. However, it would work if there are only digits.

$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = {'$_POST['pnumber']'}") or die ("Couldn't execute query: " .mysqli_error($con));

This second query below would work with both digits and characters after using a variable.

$test = $_POST['pnumber'];                  
$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = '$test'") or die ("Couldn't execute query: " .mysqli_error($con)); 

Upvotes: 0

Views: 902

Answers (1)

Perry
Perry

Reputation: 11700

replace this:

$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = {'$_POST['pnumber']'}") or die ("Couldn't execute query: " .mysqli_error($con));

With this:

$result = mysqli_query($con, "DELETE FROM Tools WHERE PartNumber = '" . $_POST['pnumber'] ."'") or die ("Couldn't execute query: " .mysqli_error($con));

Notice I did not take care of sql injection above

Even better is to use prepare statements that will secure your querys, in your case it will be something like this:

$sql= 'DELETE FROM Tools WHERE PartNumber= ?';      

$stmt = $con->prepare($sql); 
$stmt->bind_param('i', $_POST['pnumber']);
$stmt->execute();

Upvotes: 1

Related Questions