无法使用PHP将变量插入SQL数据库

时间:2016-01-12 18:45:21

标签: php sql variables

我需要使用PHP将信息从HTML文档保存到SQL数据库。但是,我对变量的连接有问题。这就是我到目前为止所做的:

$requete= $sql->prepare"(INSERT INTO personnes (name,surname,street,city,country) 
                         VALUES". "("$name.$surname.$street.$city.$country."))";

到目前为止,这是构成问题的唯一部分,因为其余代码在我首次亮相时正在运行。我究竟做错了什么?

2 个答案:

答案 0 :(得分:0)

使用,分隔值。 .(DOT)用于连接字符串。

$requete= $sql->prepare("INSERT INTO personnes (name,surname,street,city,country) 
        VALUES ('$name','$surname','$street','$city','$country')");

这是您的查询。你也需要绑定参数。

$sql->bind_param($name,$surname,$street,$city,$country);

了解更多信息read

答案 1 :(得分:-2)

使用?作为值并将值绑定到查询。我实际上不能给你一个例子。

PHP documentation

中也对此进行了描述

您可以在mysqli Statement Object中使用参数绑定,以便在Documentation的面向对象样式的第一个示例中显示它:

示例#1面向对象的样式

<?php
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);

$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* Clean up table CountryLanguage */
$mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'");
printf("%d Row deleted.\n", $mysqli->affected_rows);

/* close connection */
$mysqli->close();
?>

也是第二个例子中描述的程序风格。

示例#2程序样式

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$city = "Amersfoort";

/* create a prepared statement */
$stmt = mysqli_stmt_init($link);
if (mysqli_stmt_prepare($stmt, 'SELECT District FROM City WHERE Name=?')) {

    /* bind parameters for markers */
    mysqli_stmt_bind_param($stmt, "s", $city);

    /* execute query */
    mysqli_stmt_execute($stmt);

    /* bind result variables */
    mysqli_stmt_bind_result($stmt, $district);

    /* fetch value */
    mysqli_stmt_fetch($stmt);

    printf("%s is in district %s\n", $city, $district);

    /* close statement */
    mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);
?>