简体   繁体   中英

Inserting variable into sql string variable

$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";
        }

due that code I got an query error

Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'chs_st2_rec'. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'chs_st2_rec'. ) )

I can't identify what's error and where it's.

figured it out

the code error before all of these line

reason is i used single quotes with variable

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

so i remove single quotes out and it's work

thanks everyone :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM