如何使用PHP将数据插入mysql?

时间:2015-08-15 03:14:18

标签: php mysql

我运行此代码并且浏览器报告$ sql中的语法错误,但我没有看到任何。

$sql = "INSERT INTO Recruits (name, age, college, major, college, 
        yearsOfWork, formerCompany, moreinfo) VALUES ($name, $age, $college,
        $major, $college, $yearsOfWork, $formerCompany, $moreinfo)";

2 个答案:

答案 0 :(得分:2)

试试这个

$sql = "INSERT INTO Recruits (name, age, college, major, college, yearsOfWork, formerCompany, moreinfo) VALUES ('$name', '$age', '$college', '$major', '$college', '$yearsOfWork', '$formerCompany', '$moreinfo')";

只需在值

上添加单引号即可

答案 1 :(得分:0)

首先,您必须设置数据库连接,远程或本地。

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";

if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);