gpt4 book ai didi

php - 从数据库表中提取字段数据的简单函数

转载 作者:行者123 更新时间:2023-11-30 23:15:50 25 4
gpt4 key购买 nike

我已经玩了几个小时了。我是 PHP 的新手,想设置一些函数,如果另一个字段的名称已 check out ,则通过选择一个字段从数据库表中提取信息。

database example http://img825.imageshack.us/img825/3770/pn4.png

这就是我一直在玩的东西。我不确定此时我在做什么。我已经尝试了很多不同的代码组合,但我不确定哪种组合还能继续工作。

function getSiteTitle() {
include("imp/connect.php");
$siteTitle = "SiteTitle";
$query = $db->prepare("SELECT Value FROM settings WHERE Name = ?");
$query->bind_param('s', $siteTitle);
$query->execute();
$setting = $query->fetch();
echo $setting;
}

如有任何帮助,我将不胜感激。

更新:我成功了,但不知道实际效果如何。这是更新后的代码:

function getSiteTitle() {
include("load.php");
$siteTitle = "SiteTitle";
$query = $db->prepare('SELECT `Value` FROM `Settings` WHERE `Name` = ?') or die (mysqli_error($db));
$query->bind_param('s', $siteTitle);
$query->execute();
$query->bind_result($Value);
$query->fetch();
echo $Value;
}

echo getSiteTitle();

最佳答案

please try with the following ,check your connection variables are correct.
<?php
function fetch_data(){
$user="root";
$pass="";
$dsn='mysql:dbname=mydata;host=localhost;';
try{
$db =new PDO($dsn,$user,$pass);
}
catch(PDOException $e){
echo "connection failed ".$e->getMessage();
}
//replace the code block from $user to end of catch statement because that might be within //your included file connect.php
$query=$db->prepare("SELECT Value FROM settings WHERE Name = ?");
$name="SiteSlogan";//or SiteTitle
$query->bindParam(1,$name, PDO::PARAM_STR);
$query->execute();
$query->bindColumn("Value",$value);
$query->fetch();
echo $value;
// or you can add more columns in bincolumn like
//$query->bindColumn("id",$id);
//echo $id;
}

fetch_data();
?>

关于php - 从数据库表中提取字段数据的简单函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17915123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com