PDO, $_GET, and SELECTing from MySQL Database

岁酱吖の 提交于 2020-01-14 06:01:06

问题


So I'm working on a PHP Pastebin-esque project on my freetime to learn PHP and server management, and I've run into a LOT of issues, and I haven't been able to solve them. I decided to restart from sratch on my own with the information I've gathered so far, and threw this code together.

<?php
    require 'connection.php';
        $getid = $_GET["id"];
        $sql = 'SELECT paste FROM pasteinfo WHERE id=:id';
        $stmt = $con->prepare($sql);
        $stmt->bind_param(':id', trim($_GET["id"], PDO::PARAM_INT));
        $stmt->execute();

        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo $row['paste'];
        }

?>

What I'm trying to achieve with this code is a system where a user can type the id of whatever paste they're interested in viewing in the url and have it display the pasteinfo row, which is the row that holds the paste itself. The format they should have is viewpaste.php?id=(user input).

How can I fix this code? I would also greatly appreciate if you explain whatever code you might end up putting in the comments so I can learn from it. Thanks!


回答1:


Try this;

connection.php

try{
$db = new PDO('mysql:host=localhost;dbname=database_name;charset=utf8mb4', 'database_username', 'database_password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch (PDOException $ex){
echo $ex->getMessage();return false;
}

function retrieve($query,$input) {
 global $db;
 $stmt = $db->prepare($query);
 $stmt->execute($input);
 $stmt->setFetchMode(PDO::FETCH_OBJ);   
 return $stmt;
}

To retrieve data, call the retrieve() function

Retrieval page, say display.php

require 'connection.php';
$getid = $_GET["id"];
$result=retrieve("SELECT paste FROM pasteinfo WHERE id=?",array($getid));
$row=$result->fetch();
//To get paste column of that id
$paste=$row->paste;
echo $paste;


来源:https://stackoverflow.com/questions/40099530/pdo-get-and-selecting-from-mysql-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!