dsfds656545 2012-05-12 12:27
浏览 18
已采纳

php + mysql:创建查询

Supose, that you need to insert into table of db row with values $a, $b, $c, the values can be unsafe, name of table is stored in the class performing the operation as constant. It's possible to make query as follows

$query = "INSERT INTO `" . self::TABLE . '` ' .
    "(a, b, c) VALUES (" .
    . intval(a) .
    ",'" . mysql_real_escape_string(b) . "'" .
    ",'" . mysql_real_escape_string(b) . "')";

Here's the question: is there a more elegant way to create a query?

  • 写回答

4条回答 默认 最新

  • dqpwdai095465 2012-05-12 12:30
    关注

    It's called prepared statements, it exists in MySQLi (good) or PDO (better). I'll add the common thing I add in comments for people who use mysql_*:

    Please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you care to learn, here is a quite good PDO-related tutorial.

    While it is possible to do in mysql_* functions, I highly (really EPICLY) recommend against it.


    In PDO, your code would look like this:

    $query = "INSERT INTO `" . self::TABLE . "` (a, b, c) VALUES (:a, :b, :c);";
    
    $statement = $db_connection->prepare($query);
    
    $statement->bindParam(":a", $a);
    $statement->bindParam(":b", $b);
    $statement->bindParam(":c", $c);
    
    $statement->execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 mySQL5.7.34安装遇到的问题
  • ¥15 结构功能耦合指标计算
  • ¥20 visual studio中c语言用ODBC链接SQL SERVER
  • ¥50 AI大模型精调(百度千帆、飞浆)
  • ¥15 非科班怎么跑代码?如何导数据和调参
  • ¥15 福州市的全人群死因监测点死亡原因报表
  • ¥15 Altair EDEM中生成一个颗粒,并且各个方向没有初始速度
  • ¥15 系统2008r2 装机配置推荐一下
  • ¥15 悬赏Python-playwright部署在centos7上
  • ¥15 psoc creator软件有没有人能远程安装啊