大家好,我开始一个新的代码,但我不能找出我的代码上的错误
代码当我发送一个调用到我的脚本像这样http://www.mywebsite.com/savedata.php?user_id=abc
这是我的代码
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
$servername = "localhost";
$username = "user_name";
$password = "pass";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb_name", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_GET['user_id'])){
//$user_id = intval($_GET['user_id']);
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
try {
$dbh = new PDO("mysql:host=$servername;dbname=db_name", $username, $password);
$user_id = @$_GET['user_id'];
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (user_id) VALUES ('".$_POST["user_id"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
$sql->execute(array($user_Id));
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your ID was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your id wasnt passed in the request.';
}
// close MySQL connection
$conn = null;
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
你检查$ _GET [' user_id ']…
if(isset($_GET['user_id'])){
…但是你试图访问$_POST['user_id']:
$sql = "INSERT INTO users (user_id) VALUES ('".$_POST["user_id"]."')";
注::在查询中,您可以简单地使用$user_id,给定的一些行之前,你做:
$user_id = @$_GET['user_id'];
您有时使用$_GET["user_id"]
,但有时使用$_POST["user_id"]
。如果你总是通过GET发送数据,你应该总是使用$_GET["user_id"]
。
或者直接使用$_REQUEST["user_id"]