마다 업데이트 된 코드는 첫째로 당신의 잘못가는 곳을보고, 현재의 코드를 해부 할 수 있습니다.
<?php
include_once('includes/config.php');
/*
$id is not set anywhere before its used so this if statement will not fire,
if you are attempting to get this $id from a url parameter then you need
to set it first from $_GET['id'] global
*/
if($id != "") {
$id = mysql_real_escape_string($id);
$sql = mysql_query("SELECT * FROM news WHERE id = '$id'");
}
/*
This piece of code will fire but where is $sql set?
The mysql_query() function expects a string containing your sql query
so the subsequent lines of code will fail because of this
*/
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)){
//this block is in the wrong place
if(isset($_GET['id']));
echo $res['body'];
}
?>
아이디어는 먼저 URL에서 $_GET['id']
을 예컨대 사용자 입력을받을 가치가 당신이 찾고있는 무엇인가를 확인한 다음 쿼리를 구축하는 것입니다.
mysql_*
기능이 더 이상 사용되지 않으므로 PDO를 사용한 예를 보여 드리겠습니다. mysqli를 사용할 수 있지만, 항상사용자 값이 데이터베이스에 연결될 때마다 준비된 쿼리를 사용해야합니다. 이것은 불쾌한/실수로 SQL 인젝션을 중지하는 것입니다.
<?php
// make the connection to the database using PDO
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=the_awsome_db', 'yourusername', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->exec("SET CHARACTER SET utf8");
} catch(PDOException $e) {
exit('Sorry there is a problem with the database connection :' . $e->getMessage());
}
// sanitize user input - expecting an int
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
if (is_numeric($id)) {
// now lets query the database with the param id from the user
// prepare the query, using a placeholder
$stmt = $db->prepare('SELECT body,
some_other_column
FROM news
WHERE id = :placeholder_id');
// bind the placeholder with the value from the user
$stmt->bindParam(':placeholder_id', $id);
// execute the prepared query
$stmt->execute();
// fetch the result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// result not empty - display
if (!empty($result)) {
// display your result, use print_r($result) to view the whole result set if unsure
echo $result['body'];
} else {
// no matching id found in the db, do something
echo 'No results found';
}
} else {
// do something as user input is not a number
exit(header('Location: ./index.php'));
}
?>
는 좀 더 자습서를보고 처음 데이터베이스와 모든 좋은 물건을 튀기기 전에의 묘리를 터득해야 할 수 있습니다 사용자로부터 매개 변수를 얻기의 당신의 확신이 경우는, 도움이되기를 바랍니다.
어디에서'$ id'를 정의하고 있습니까? –
추천 제안, [** 새 코드 **에서 mysql_ * 함수를 사용하지 마십시오.] (http://bit.ly/phpmsql). 그들은 더 이상 유지되지 않으며 [공식적으로 사용되지 않습니다] (http://j.mp/XqV7Lp). [** 빨간색 상자 **] (http://j.mp/Te9zIL)를 참조하십시오. 대신 [* prepared statements *] (http://j.mp/T9hLWi)에 대해 알아보고 [PDO] (http://php.net/pdo) 또는 [MySQLi] (http://php.net/)를 사용하십시오. mysqli) - [이 기사] (http://j.mp/QEx8IB)는 어떤 결정을 내리는 데 도움이 될 것입니다. PDO를 선택하면 [여기는 좋은 튜토리얼입니다] (http://j.mp/PoWehJ). –
누군가가 나를 놀라게 할 수있는 방법을 안내 할 수 있다면 나는 PHP와 MySQL에 정말 새로운 것이다. –