2016-01-12 87 views
1

我需要使用PHP將信息從HTML文檔保存到SQL數據庫。但是,我有一個與變量串聯的問題。這是我到目前爲止有:使用PHP將變量插入SQL數據庫時遇到困難

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

到目前爲止,這是擺在問題的唯一組成部分,作爲代碼的其餘部分工作時,我登場。我究竟做錯了什麼?

+1

此代碼有很多問題。你不想連接開始。你希望每個值都被插入到數據庫中,對嗎?這也是注意使用預準備語句的正確方法。 http://php.net/manual/en/pdo.prepared-statements.php或http://php.net/manual/en/mysqli.quickstart.prepared-statements.php我認爲這也應該扔500 。 – chris85

+2

你需要學習基本的PHP語法,以及如何不讓自己容易受到[sql注入攻擊](http://bobby-tables.com) –

+0

如果有人最常見的評論,這是「sql注入攻擊」。這讓我想知道爲什麼不明顯這是做錯事情的錯誤方式。比如,PHP應該棄用它的使用或完全禁止它。不知何故。 – durbnpoisn

回答

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

也許在這個聲明中也值得一提SQL注入漏洞,並且使用準備好的語句來克服這個問題。 – Benjy1996

+1

你在這裏糾正了其他的一些問題(SQL字符串需要引號,'prepare'是一個函數)。準備好的聲明仍然被錯誤地使用。 – chris85

+1

是的。你是對的。這很容易被sql注入。我只是指導當前代碼中的錯誤。 – urfusion

-2

使用?的價值和你的價值觀綁定到查詢。我其實不能給你一個例子。

這也是在PHP documentation描述:

可以使用參數與所述的mysqli語句對象它是如何在第一個例子中示出了用於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); 
?> 
相關問題