【问题标题】:Inserting variable into sql string variable将变量插入sql字符串变量
【发布时间】:2015-08-07 09:01:44
【问题描述】:
$sql = "insert into dbo.".$st_tab." (bike_id,st_id";
        if($st_tab === "st1_rec_id"||$st_tab === "st2_rec_id"||$st_tab ==="st3_rec_id")
        {
            $sql .= ",ln_id";
        }
        $sql .= ",times,date) values (?,?";
        if($st_tab === "st1_rec_id"||$st_tab === "st2_rec_id"||$st_tab ==="st3_rec_id")
        {
            $sql .= ",?";
        }
        $sql .= ",?,?)";
        echo $sql;
        if($st_tab === "st1_rec_id"||$st_tab === "st2_rec_id"||$st_tab ==="st3_rec_id")
        {
            $var = array($bike_id,$station,$line,$time,$date);
        }
        else
        {
            $var = array($bike_id,$station,$station,$time,$date);
        }
        $insert = sqlsrv_query($conn,$sql,$var);
        if($insert === false)
        {
            die(print_r(sqlsrv_errors(),true));
        }
        else
        {
            foreach($var as $x => $a)
            {
                echo $x." : ".$a." ";
            }
            echo "<br> 1 Record Added";
        }

由于该代码,我收到了查询错误

数组([0] => 数组([0] => 42000 [SQLSTATE] => 42000 [1] => 102 [代码] => 102 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL 服务器]“chs_st2_rec”附近的语法不正确。 [留言] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]语法不正确 在“chs_st2_rec”附近。 ))

我无法确定什么是错误以及它在哪里。

【问题讨论】:

  • 我尝试在 "$sql .= ",?,?)";" 之后打印出组装好的 SQL 字符串我已经回显 $sql 但它没有显示。谢谢
  • 弄清楚实际发生了什么。如果您甚至无法打印出 SQL 字符串,那么这不是正确的代码摘录。 (值得注意的是,没有 chs_st2_rec 可见;但这就是错误消息的含义)。如果这实际上不是相关代码,您将不会得到答案。请花更多时间添加细节(请参阅How to askWriting the perfect questionMCVE...)
  • 啊,我明白了,这是我的错,这段代码之前的代码错误,我完成了,我已经编辑了 ** $sql = "select '$st_char' from '$st_tab' where bike_id像'$bike_id'"; ** into **$sql = "select $st_char from $st_tab where bike_id like '$bike_id'"; ** 这就是工作:)。谢谢

标签: php sql-server


【解决方案1】:

想通了

所有这些行之前的代码错误

原因是我在变量中使用了单引号

$sql = "select '$st_char'
            from '$st_tab'
            where bike_id like '$bike_id'";

所以我删除了单引号,它的工作

谢谢大家:)

【讨论】:

    猜你喜欢
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多