使用PHP将复选框输入放入MySQL表列

时间:2017-01-09 23:31:46

标签: php mysql

<?php
session_start();
$servername = "localhost";
$username = "_admin";
$password = "";
$dbname = "_users";

$value = $_POST['userTel'];
$sesh = $_SESSION['userSession'];
$checkbox1=$_POST['site'];  
$chk="";  
foreach($checkbox1 as $chk1)
{  
    $chk .= $chk1.",";  
}  

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // begin the transaction
    $conn->beginTransaction();
    // our SQL statements
    $conn->exec("UPDATE tbl_users SET userTel = '$value' WHERE userID = '$sesh'");
    $conn->exec("UPDATE tbl_sites SET siteName ('$chk')");

    // commit the transaction
    $conn->commit();
    echo "all's good ^.^";
}
catch(PDOException $e)
{
    // roll back the transaction if something failed
    $conn->rollback();
    echo "Error: " . $e->getMessage();
}

$conn = null;
?>

这是我的代码,这是我的错误:

  

错误:SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与您的MariaDB服务器版本对应的手册,以便在第1行的'('kith,')'附近使用正确的语法

(kith是输入值中的1)

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

更传统的准备方式可能吗?

session_start();
$servername = "localhost";
$username = "_admin";
$password = "";
$dbname = "_users";

$value = $_POST['userTel'];
$sesh = $_SESSION['userSession'];
$checkbox1 = $_POST['site'];
$chk = "";

foreach ($checkbox1 as $chk1) {
    $chk .= $chk1 . ",";
}
/* making sure there not the last , anyway */
$chk = rtrim($chk, ",");

/* setting conn */
try {
    $conn = new PDO('mysql:host=' . $servername . ';dbname=' . $dbname . ';charset=UTF8', $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

/* prepared stmts */
$sql1 = "UPDATE tbl_users SET userTel = ? WHERE userID = ?";
$sql2 = "UPDATE tbl_sites SET siteName = ?";
$stmt1 = $conn->prepare($sql1);
$stmt2 = $conn->prepare($sql2);

/* bindings */
$stmt1->bindParam(1, $value, PDO::PARAM_STR);
$stmt1->bindParam(2, $sesh, PDO::PARAM_STR);
$stmt2->bindParam(1, $chk, PDO::PARAM_STR);

/*exec*/
$sql1->execute();
$sql2->execute();

答案 1 :(得分:0)

您必须从,删除最后$chk

试试这个。

if(strlen($chk)>0){
   substr($chk, 0, strlen($chk)-1);
}