doulang6013 2015-02-12 07:48
浏览 65

如何在SQL查询中插入php变量?

I've found a lot of answers for this that don't seem to work for me. When I have apostrophes around the variables $message and $email and $date like

    'VALUES ('$message', '$email', '$date')';

it tells me

Parse error: syntax error, unexpected '$message' (T_VARIABLE)

When I remove them, I get something like Could not enter data: Unknown column '$message' in 'field list'. I've tried to insert

    $message = mysql_real_escape_string($message);    
    $email = mysql_real_escape_string($email);
    $date = mysql_real_escape_string($date);

with " " around the variables like

'VALUES ("$message", "$email", "$date")';

which gets rid of the error message but now, instead of the input from the html form, i'm getting literally "$message" in my database.

What is it that I'm doing wrong? My simple objective is just to take an email, a message, and the date, and put it in a database. Please help! Thank you!

Here is the complete code I have:

     <?php
if($_POST && isset($_POST['email'], $_POST['essay'])) {


    $dbhost = 'localhost';
    $dbuser = 'root';
    $dbpass = 'password';

    $conn=mysql_connect($dbhost, $dbuser);
    if(! $conn)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db("Ink", $conn);

    date_default_timezone_set("America/New_York");
    $message = $_POST['essay'];
    $email = $_POST['email'];
    $date = date("y-m-d h:i:sa");


    $sql = 'INSERT INTO inktable '.
            '(writings, email, date) '.
            'VALUES ('$message', '$email', '$date')';

    mysql_select_db('ink');
    $retval = mysql_query($sql, $conn);
    if(! $retval)
    {
        die('Could not enter data: ' .mysql_error());
    }

    mysql_close($conn);
}
?>
  • 写回答

2条回答 默认 最新

  • dongxiao3694 2015-02-12 07:52
    关注

    I think you need those little dots:

      ('.$message.', '.$email.', '.$date.')';
    

    Or:

     ("'.$message.'", "'.$email.'", "'.$date.'")';
    
    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?