要使用PHP获取列中的所有值,您可以使用以下步骤:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sql = "SELECT columnName FROM myTable";
$stmt = $conn->prepare($sql);
$stmt->execute();
fetchAll()
方法来获取查询结果中的所有值。这将返回一个包含所有行的数组。$result = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($result as $value) {
echo $value . "<br>";
}
将以上代码段组合在一起,您将获得一个完整的示例,用于使用PHP从数据库列中获取所有值。
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT columnName FROM myTable";
$stmt = $conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($result as $value) {
echo $value . "<br>";
}
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
请注意,您需要根据实际情况替换$servername
、$username
、$password
、$dbname
、myTable
和columnName
这些变量的值。
领取专属 10元无门槛券
手把手带您无忧上云