2017-01-09 31 views
0
<?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; 
?> 

這是我的代碼,這就是會回到我的錯誤:把複選框,輸入到MySQL表列與PHP

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '('kith,')' at line 1

(骨肉是輸入值1)

我在這裏做錯了什麼?

+0

它不應該是'SITENAME =「$ chk'',然後你可能要一個'where'條款,所以你不更新整個表..還有你是開放的SQL注入。 – chris85

+1

**警告**:使用PDO時,您應該使用帶有佔位符值的[prepared statements](http://php.net/manual/en/pdo.prepared-statements.php),並提供任何用戶數據作爲單獨的參數。在此代碼中,您可能會遇到嚴重的[SQL注入漏洞](http://bobby-tables.com/)。切勿使用字符串插值或連接,而應使用[準備語句](http://php.net/manual/en/pdo.prepared-statements.php),並且絕對不要將'$ _POST'或'$ _GET'數據直接放入您的查詢。有關此問題和其他問題的指導,請參閱[PHP正確方法](http://www.phptherightway.com/)。 – tadman

回答

0

更傳統的準備stmt可能的方式?

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(); 
0

你必須從$chk除去塔最後,

試試這個。

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