dounie0889 2012-12-14 12:55
浏览 49
已采纳

变量声明上的Php阻塞(w / psql)

I'm kind of a newbie in PHP but even I think this is not normal.

My code blocks in the followoing line all the time:

$insert = 'INSERT INTO boleia VALUES ('.$nick.', '.$data_format.', '.$custo.', '.$dest_origem.', '.$dest_destino.', NULL, '.$matricula.');';

I tried with double quotes and with the variables inside those double quotes and nothing.

Any idea?

  • 写回答

6条回答 默认 最新

  • dqifn68206 2012-12-14 13:06
    关注

    Your PHP code is syntactically correct but the generated SQL is not because you are not using quotes to delimit the values.

    You can do this:

    $insert = 'INSERT INTO boleia VALUES ("'.$nick.'", "'.$data_format.'", "'.$custo.'", "'.$dest_origem.'", "'.$dest_destino.'", NULL, "'.$matricula.'");';
    

    or this:

    $insert = "INSERT INTO boleia VALUES ('".$nick."', '".$data_format."', '".$custo."', '".$dest_origem."', '".$dest_destino."', NULL, '".$matricula."');';
    

    you can also do this:

    $insert = "INSERT INTO boleia VALUES ('$nick', '$data_format', '$custo', '$dest_origem', '$dest_destino', NULL, '$matricula');";
    

    but none of that ways are recommended because you are vulnerable to SQL Injections!

    How to prevent SQL Injections?

    To prevent that you must escape the values using the appropriate function for your DB, for example, since you are using PostgreSQL you must use pg_escape_string() for every value:

    $insert = 'INSERT INTO boleia VALUES ("'.pg_escape_string($nick).'", "'.pg_escape_string($data_format).'", "'.pg_escape_string($custo).'", "'.pg_escape_string($dest_origem).'", "'.pg_escape_string($dest_destino).'", NULL, "'.pg_escape_string($matricula).'");';
    

    An other way would be using pg_prepare() with pg_execute()

    pg_prepare($dbconn, "my_insert", 'INSERT INTO boleia VALUES ($1, $2, $3, $4, $5, NULL, $6);');
    pg_execute($dbconn, "my_insert", array($nick, $data_format, $custo, $dest_origem, $dest_destino, $matricula));
    

    Or even using pg_query_params()

    pg_query_params($dbconn, 'INSERT INTO boleia VALUES ($1, $2, $3, $4, $5, NULL, $6);',
                    array($nick, $data_format, $custo, $dest_origem, $dest_destino, $matricula));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料