php - 使用 PDO 从 MySQL 数据库获取单个结果

标签 php html mysql pdo

好吧,对于初学者来说,我在 MySQL 中有一个表,其中包含“条形码”、“描述”和“数量”列。我有两个页面,1 个 HTML 和 1 个 PHP。 HTML 中有一个表单可以接受条形码扫描或手动文本输入。基于该条目,我希望它返回一行,从在 HTML 表单中输入的条形码开始。到目前为止,我可以输入任何内容,它将返回整个表格。

HTML 看起来像这样:

<head>
<font color="00CC00">
<title>Search</title>
</head>

<body bgcolor="000000">

<h2>Find Product</h2>

<form name="search" method="post" action="Barcode Search.php">
<input type="text" name="find" placeholder="Click to Scan" /> 


<input type="submit" name="search" value="Submit" />
</form>

</body>

</html>

简短、甜蜜、切中要点! .PHP 看起来像这样:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<title>Inventory List</title>

<body bgcolor="000000">
<font color="00cc00">

 <?php 
//Table
echo "<table style='border: solid 1px green;'>";
echo "<tr><th>Barcode</th><th>Description</th><th>Quantity</th></tr>";

class TableRows extends RecursiveIteratorIterator {
    function __construct($it) {
        parent::__construct($it, self::LEAVES_ONLY);
    }

    function current() {
        return "<td style='width:150px;border:1px solid green;'>" . parent::current(). "</td>";
    }

    function beginChildren() {
        echo "<tr>";
    }

    function endChildren() {
        echo "</tr>" . "\n";
    }
} 
//Connection Info
$servername = "127.0.0.1";
$username = "XXXX";
$password = "XXXXX";
$dbname = "test";


//Connection Started, Data pulled
try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare("SELECT * FROM inventory ");
    $stmt->execute();

// set the resulting array to associative
    $result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
    foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
        echo $v;
    }
}

    //Error Check

catch(PDOException $e) {
    echo "Error: " . $e->getMessage();
}
// Take Text entry and fetch the SQL Row


//Kill Connection 
$conn = null;
echo "</table>";
?> 
</center>
</body>
</html>

我非常感谢您指出正确的方向! 提前致谢!

最佳答案

SELECT * FROM inventoryinventory 表中选择所有内容,没有细化或限制。我猜你想要这样的东西:

$stmt = $conn->prepare("SELECT * FROM inventory WHERE barcode = ? LIMIT 1");
$stmt->bindParam("s", $_POST["find"]); // 's' means it's a string
$stmt->execute();

http://php.net/manual/en/mysqli.prepare.php

关于php - 使用 PDO 从 MySQL 数据库获取单个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27930150/

相关文章:

php - SQL 值为 0,即使它们存在

php - Web 服务应用程序 - 应用程序安全性(登录、用户数据等)

PHP/MYSQL - 只能显示行中的一个元素,可能是问题?

javascript - 在 woocommerce 感谢页面的 head 标签中插入 javascript 代码

javascript - 有没有办法在直播时调整图像大小?

javascript - jQuery - 在多个 ID 上使用相同的函数 (ToggleNav/Dropdown)

html - 如何使用 CSS/HTML/JAVA 制作文本幻灯片

php - 将csv文件导入homestead laravel中的mysql表字段

mysql - 如何选择在另一个表中具有所有或没有对应值的行?

php - 得到非法的排序规则混合错误