2013-09-06 5 views
0

나는이 뉴스 시스템을 가지고 있지만 어떻게 이런 식으로 할 수 있는지 알 수 없다 : news.php?id=1 그러면 뉴스 ID 1이 출력 될 것이다.MYSQL 및 PHP 뉴스 시스템

지금까지이 있습니다

그것은 데이터베이스에 연결
<?php 
include_once('includes/config.php'); 
if($id != "") { 
    $id = mysql_real_escape_string($id); 
    $sql = mysql_query("SELECT * FROM news WHERE id = '$id'"); 
} 
$res = mysql_query($sql); 
while($row = mysql_fetch_assoc($res)){ 
if(isset($_GET['id'])); 
    echo $res['body']; 
} 
?> 

는 (세부 사항은 설정에 저장됩니다).

+2

어디에서'$ id'를 정의하고 있습니까? –

+1

추천 제안, [** 새 코드 **에서 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). –

+0

누군가가 나를 놀라게 할 수있는 방법을 안내 할 수 있다면 나는 PHP와 MySQL에 정말 새로운 것이다. –

답변

3

? URL에 GET 항목이 있습니다. 이 옵션을 사용합니다 :

<?php 

if (isset($_GET['id'])) { 

    $id = $_GET['id']; 
    // Rest of your code 

} 
+0

미안하지만, 나는 정말로 확신 할 수 없다. 이 일을 어떻게 해야할지. 방금 튜토리얼을 보았지만 훨씬 복잡하지는 않습니다. –

1
<?php 
include_once('includes/config.php'); 

// see if the id is set in the URL (news.php?id=) 
if(isset($_GET['id'])) { 

    // get the ID from the URL 
    // to make it safer: strip any tags (if it's a number we could cast it to an integer) 
    $id = strip_tags($_GET['id']); 

    // don't use SELECT *, select only the fields you need 
    $sql = mysql_query("SELECT body FROM news WHERE id=".mysql_real_escape_string($id)); 

    while($row = mysql_fetch_assoc($sql)) { 
     echo $res['body']; 
    } 
} else { 
    echo 'please select an article'; 
} 

난 당신이 mysql 기능을 사용하여 멀리 얻을 추천 및 mysql이 감가 상각으로 대신 mysqli을 사용하고 어쨌든 mysqli 또는 PDO을 배워야 할 것이다.

편집 : 의견

+1

당신의 시도가 더 안전하다는 것을 인정하지만, int로 형변환하려고한다면 왜 'strip_tags'를 사용해야할까요? 그래서 ''는'0'보다는'182'가됩니다 ...? 그리고 문자열이 아니라 정수라는 것을 알기 때문에 mysql_real_escape_string도 완전히 중복됩니다. – IMSoP

+0

^IMSOP이 말하는 모든 것; 또한, mysql_query()에 대한 두 번째 호출이 잘못되었다. (처음에는 이미 잘못되어 있지 않은 것처럼 리소스를 전달한다.) 쿼리가 실패하면 어떻게 될까? –

+0

감사합니다. 업데이트되었습니다. ID가 int 인 것으로 가정하고 싶지는 않습니다 (아마도 그렇 겠지만). 그래서 캐스팅을 제거했습니다. 나는 몇 년 동안 mysql을 사용하지 않았다. (나는 db 클래스를 사용한다.) 그래서 나는 꽤 녹슬었다. :) – timgavin

1

마다 업데이트 된 코드는 첫째로 당신의 잘못가는 곳을보고, 현재의 코드를 해부 할 수 있습니다.

<?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')); 
} 
?> 

는 좀 더 자습서를보고 처음 데이터베이스와 모든 좋은 물건을 튀기기 전에의 묘리를 터득해야 할 수 있습니다 사용자로부터 매개 변수를 얻기의 당신의 확신이 경우는, 도움이되기를 바랍니다.

+0

이것은 나를 위해 복잡한 방법입니다. : s –

+1

@MathiasTangre : 누군가가 당신에게 많은 도움을 주면 답장에 더 많은 노력을 기울여야합니다. 많은 질문을하기 전에 PHP에 대한 연구를해야하는지, 많은 수의 downvotes를 얻고 있기 때문에 궁금합니다. – halfer