2017-03-16 79 views
1

我想用jQuery將數據插入mySQL。代碼不會返回任何錯誤,也不會返回任何結果。請幫我解決這個問題。PHP和jQuery插入到MySQL

$(document).ready(function() { 
    $("#submit").click(function() { 
    var data; 
    var eid = 101; 
    data = "eid=" + eid; 
    for (i = 0; i <= 10; i++) { 
     data += "&Text_" + (i + 1) + "=" + $("#Text_" + (i + 1)).val(); 
     data += "&Amount_" + (i + 1) + "=" + $("#Amount_" + (i + 1)).val(); 
    } 
    $.ajax({ 
     type: "POST", 
     url: "process.php", 
     cache: false, 
     data: data, 
     dataType: "json", 
     success: function(response) { 
     if (!response.error) { 
      $("#msg").addClass('alert-success').html(response.msg); 
     } else { 
      $("#msg").addClass('alert-danger').html(response.msg); 
     } 
     } 
    }); 
    }); 
}); 
<tr> 
    <td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td> 
    <td><input type="text" value="1001.00" name="Amount[]" id="Amount_1" /></td> 
</tr> 
<tr> 
    <td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td> 
    <td><input type="text" value="1002.00" name="Amount[]" id="Amount_2" /></td> 
</tr> 
<tr> 
    <td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td> 
    <td><input type="text" value="1003.00" name="Amount[]" id="Amount_3" /></td> 
</tr> 

我也加入process.php片段,以便知道哪裏是錯誤。

process.php

$eid=$_POST['eid']; 
$length = sizeof($_POST["Text"]); 
$i=1; 
while ($i<=$length){ 
    if(!empty($_POST['Text'][$i])) { 
     $Text = $_POST['Text'][$i]; 
     $Amount = $_POST['Amount'][$i]; 

     $msg = array('status' => !$error, 'msg' => 'Failed! updation-1');   
     if(!$error) { 
      $sql = "UPDATE TblCustom SET Text='" . $Text . "', Amount='" . $Amount ."' WHERE ID='$eid'";     
      $status = mysqli_query($conn, $sql) or die("database error:". mysqli_error($conn)); 
      $msg = array('error' => $error, 'msg' => 'Success! updation : '. $sql); 
     } 
     else { 
      $msg = array('error' => $error, 'msg' => 'Failed! updation-2 '); 
     } 

    } 
    echo json_encode($msg); 

} 

感謝

+4

什麼是您指定'數據類型,它使用的是在process.php –

+0

代碼:「JSON」',而是你正在使用的實際格式是'應用程序/ x-WWW的形式,urlencoded' (名稱=值,用&分隔)。 這可能是你的PHP腳本失敗的原因。刪除'dataType'屬性並檢查是否有幫助。 –

+0

@RohitAilani process.php添加片段 – Gawai

回答

1

你有3個問題。

問題一和二是相關的。首先,您指定的是dataType: 'json',但是您的數據格式爲application/x-www-form-urlencoded。其次,你的PHP腳本預計數據將在以下格式:

$_POST = [ 
    'Text' => ['text_1', 'text_2', 'text_3'], 
    'Amount' => ['amount_1', 'amount_2', 'amount_3'] 
]; 

雖然數據看起來是這樣的:

$_POST = [ 
    'Text_1' => 'text_1', 
    'Text_2' => 'text_2' 
    // and so on 
]; 

單修復這個問題的方法如下:

$(document).ready(function() { 
    $("#submit").click(function() { 

    const data = { 
     // we are grabbing all inputs with name=Text[] 
     // and mapping them to array containing their values. 
     // The `...` is a spread operator introduced 
     // with the new js standard (ES6), 
     // that converts jQuery object to regular javascript 
     // array of inputs. 
     // you can do all of this with a for loop, but the map way 
     // is prefered 
     Text: [...$('input[name="Text[]"]')].map(input => input.value), 
     Amount: [...$('input[name="Amount[]"]')].map(input => input.value) 
    } 

    $.ajax({ 
     type: "POST", 
     url: "process.php", 
     cache: false, 
     data: data, 
     dataType: "json", 
     success: function(response) { 
     if (!response.error) { 
      $("#msg").addClass('alert-success').html(response.msg); 
     } else { 
      $("#msg").addClass('alert-danger').html(response.msg); 
     } 
     } 
    }); 
    }); 
}); 

第三個問題是已經創建了SQL注入漏洞。這意味着一些壞人可以注入和SQL語句到Text變量,然後你直接把你的SQL更新,因此他可以做他想做的任何事情(例如,刪除所有數據庫)。

More on SQL Injection

的解決方案是簡單:使用PDO和bindValue方法。

$dsn = 'mysql:dbname=testdb;host=127.0.0.1'; 
$user = 'dbuser'; 
$password = 'dbpass'; 

try { 
    $conn = new PDO($dsn, $user, $password); 
} catch (PDOException $e) { 
    // 500 means internal server error 
    // that's handy information for the client-side 
    http_send_status(500); 
    echo json_encode([ 
     'error' => [ 
      'message' => 'Unable to connect to database' 
     ] 
    ]); 
    exit; 
} 

$eid = $_POST['eid']; 
$Text = $_POST['Text'][$i]; 
$Amount = $_POST['Amount'][$i]; 

$sql = "UPDATE TblCustom SET Text = :text, Amount = :amount WHERE ID = :id"; 
$stmt = $conn->prepare($sql); 

$stmt->bindValue(':text', $Text); 
$stmt->bindValue(':amount', $Amount); 
$stmt->bindValue(':id', $eid); 

if (!$stmt->execute()) { 
    // 400 means something went wrong when updating 
    // also a handy information for the client-side 
    http_send_status(400); 
    echo json_encode([ 
     'error' => [ 
      'message' => 'Unable to update' 
     ] 
    ]); 
    exit; 
} 

// 204 measn everything went okay, and we don't return anything 
http_send_status(204); 
exit; 

提示:如果您要發送正確的狀態碼jQuery的,您可以處理這樣的錯誤:

$.ajax({ 
    // ... 
    success: function(response) { 
     // this code will be executed 
     // only when status code == 2xx 
    }, 
    error: function(response) { 
     // this code will be executed 
     // only when status code == 4xx | 5xx (if I remember correctly) 
    }, 
    always: function(response) { 
     // this code will be executed no matter what 
     // as the name implies 
    }, 
}); 

所以沒有需要額外的if語句。

+0

感謝SQL注入部分。給定的代碼是一個很好的例子如何不做網站和數據庫之間的通信 – Serverfrog

+0

@Kamil Latosinski感謝代碼和信息的SQL注入,這仍然在測試階段將照顧安全措施根據您的建議。我沒有找到任何對「$ i」的引用。** $ Text = $ _POST ['Text'] [$ i]; ** – Gawai

+0

好吧,沒有一個。 PHP代碼示例僅演示瞭如何在您的案例中使用PDO。您必須根據需要調整代碼。 –

0
index.php 
<!DOCTYPE html> 
<html> 
<head> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
</head> 
<body> 
<form id="form_signup" name="form_signup"> 
    <tr> 
    <td><input type="text" value="Allowance1 " name="Text[]" id="Text_1" /></td> 
    <td><input type="text" value="1001.00" name="SAmount[]" id="Amount_1" /></td> 
</tr> 
<tr> 
    <td><input type="text" value="Allowance 2" name="Text[]" id="Text_2" /></td> 
    <td><input type="text" value="1002.00" name="SAmount[]" id="Amount_2" /></td> 
</tr> 
<tr> 
    <td><input type="text" value="Allowance 3" name="Text[]" id="Text_3" /></td> 
    <td><input type="text" value="1003.00" name="SAmount[]" id="Amount_3" /></td> 
</tr> 
<input type="submit" name="signup" value="Sign Up!"/> 
</form> 
<script> 
$(document).ready(function() { 
    $("#form_signup").click(function() { 
     $.ajax({ 
     type: "POST", 
     url: "process.php", 
     cache: false, 
     data: $(this).serialize(), 
     success: function(response) { 
      alert(response); 
     if (!response.error) { 
      $("#msg").addClass('alert-success').html(response.msg); 
     } else { 
      $("#msg").addClass('alert-danger').html(response.msg); 
     } 
     } 
    }); 
    }); 
}); 
</script> 

</body> 
</html> 

process.php 
<?php 
print_r($_POST); 
?> 
+0

對你做了什麼或者是什麼問題的解釋?一個代碼塊本身並不是那麼有用。 –

+0

@Nikit Barochiya數據:$(this).serialize(),沒有幫助 – Gawai

+0

工作正常並且serialize()獲取表單中的所有數據。檢查js文件工作是否正常 –