2017-03-16 10 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 snippetが追加されました – Gawai

答えて

1

あなたは3つの問題を抱えています。

問題番号1,2は関連しています。まず、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); 
     } 
     } 
    }); 
    }); 
}); 

3番目の問題は、SQLインジェクションの脆弱性が作成されていることです。つまり、いくつかの悪い人がText変数にSQL文を挿入し、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; 

はヒント:

$.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 
    }, 
}); 

その場合は、追加書類のための必要はありません:あなたはjQueryのは、あなたがこのようなエラーを処理することができます正しいステータスコードを送信する場合。

+0

SQLインジェクションパートをありがとう。与えられたコードは良い例でしたどのようにWebサイトとデータベース間の通信をしないでください – Serverfrog

+0

@カミルLatosinskiは、SQLインジェクションのコードと情報のおかげで、これはまだあなたの助言に従ってセキュリティ対策の世話をするテスト段階です。私は '$ i'への参照を見つけることはできません。** $ Text = $ _POST ['Text'] [$ i]; ** – Gawai

+0

まあ、ないです。あなたのケースでPDOを使用する方法をPHPコードサンプルで示しています。必要に応じてコードを調整する必要があります。 –

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データ:$(この).serialize()は、すべてのデータを形成し得る)( – Gawai

+0

作業が適切であるヘルプとシリアライズされません。 jsファイルの作業が正しくチェックされている –

関連する問題