dongmiao4733 2009-08-26 23:04
浏览 37
已采纳

使用PHP在MySQL INSERT QUERY中检查变量存在的简明方法

I am writing a PHP script to add items to a shopping basket. My shopping basket table has fields for the userid, product id, session id, notes and a few others. Some of the fields can be blank. For example:

if someone isn't signed in, then I will store their session id in the table and, if they sign in, add their userid so I have a permanant way to match the items in the table to the user. If they are, I'll add the userid. When it comes to the INSERT query, can I do something like this:

$add_sql = "INSERT into sessionBasket (userid) VALUES ( '". isset($_SESSION["userid"]) ? $_SESSION["userid"] : "") ."'";

It would save me so much time on variable checking and branching because people could be signed in or not, items could have notes or not, that sort of thing.

  • 写回答

1条回答 默认 最新

  • douqiang7462 2009-08-26 23:12
    关注

    Yikes! SQL Injection! you could lose your whole database

    You should be looking at prepared statements for your sql insertion.

    You need to use the mysqli interface but it goes like this:

    $statement = $db_connection->prepare("insert into ... VALUES(?)");
    $statement->bind_param("id", $sid);
    $statement->execute();
    

    This will prevent sql injection attacks.

    At an absolute minimum you should at least escape the string.

    $sid = isset($_SESSION[userid]) ? mysql_real_escape_string($_SESSION[userid])) : '';
    $add_sql = "insert into ... values($sid)";
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置