JavaScript PHP $ _Get问题

时间:2015-10-19 05:32:20

标签: javascript php mysql

所以我有一个JavaScript函数,它使用asyncronous方法调用PHP文件。这是我的代码

的JavaScript

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() { 
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
        callback (xmlHttp.responseText);
}
xmlHttp.open("GET", "http://127.0.0.1/formulario/insertReporte.php?"+'nombreAlumno='+nombreAlumno+'&noCta='+noCta+'&semestre='+semestre, true);
xmlHttp.send(null);

这是我的PHP文件

<?php

$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";

$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ($nombreAlumno,$noCta,$semestre)";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

我的问题出现在这一行$nombreAlumno = $_GET['nombreAlumno'];,因为我收到此错误

enter image description here

在我的数据库中,我的nombreAlumno字段被声明为varchar。

我知道我的连接有效,因为如果我将该行更改为$nombreAlumno = intval($_GET['nombreAlumno']);,它会将0插入到我的数据库中。

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:3)

您需要在值周围添加引号。在插入数据库之前也使用mysqli_real_escape_string以防止sql注入

$nombreAlumno=mysqli_real_escape_string($conn, $nombreAlumno);
$noCta=mysqli_real_escape_string($conn, $noCta);
$semestre=mysqli_real_escape_string($conn, $semestre);

$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";

答案 1 :(得分:0)

试试这个

<?php

$servername = "myServerName";
$username = "myUserName";
$password = "myPassWord";
$dbname = "myDb";

$nombreAlumno = $_GET['nombreAlumno'];
$noCta = intval($_GET['noCta']);
$semestre = intval($_GET['semestre']);

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO infoalumno (nombreAlumno,noCta,noSemestre)
VALUES ('".$nombreAlumno."','".$noCta."','".$semestre."')";

if ($conn->query($sql) === TRUE) {
    $last_id = $conn->insert_id;
    echo $last_id;
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>