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?

图片转代码服务由CSDN问答提供 功能建议

Supose,您需要插入db行的表,其值为 $ a,$ b,$ c ,值可能不安全,表的名称存储在执行操作的类中作为常量。 可以按如下方式进行查询

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

以下是问题:是否有更优雅的方式来创建查询?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题