Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a php variable in an sql query? Mistake in my query?

I wrote this simple code to delete a blog from the sql table. But its giving an error

Could not delete data: Unknown column '$qid' in 'where clause'

Cant understand why. $qid is the variable while just qid is the column name and its giving me this error.

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('trial1');
if(! $conn )
{
    die('Could not connect: ' . mysql_error());
}
function check_login(){
        return 12;
}
$return_array = array();
if( check_login()!=NULL){
    $qid =1;
    $sql='DELETE FROM blog_post WHERE qid = $qid';
    $retval = mysql_query($sql, $conn);
    if (!$retval){
        die('Could not delete data: ' . mysql_error());
        $return_array["success"] = 0; //If deletion unsuccessful
        echo json_encode($return_array);
    }
    else{
        $return_array["success"]=1; //If deletion successful 
        echo json_encode($return_array);
    }
}
 ?>
like image 636
user3481478 Avatar asked Mar 28 '26 20:03

user3481478


1 Answers

Variables will not be parsed under single quotes. Enclose the SQL query under double quotes ".

$sql="DELETE FROM `blog_post` WHERE `qid` = $qid"; //<-- Like this.

This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !

like image 114
Shankar Narayana Damodaran Avatar answered Mar 31 '26 09:03

Shankar Narayana Damodaran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!