我正在尝试在我的简单CMS中自动添加页面,并且不是PHP的大用户,无法弄清楚如何从MySQL数据库中获取列并从中创建一组字符串。我会解释一下。
$home=mysql_query("SELECT * FROM data WHERE callsign='home'"); //**
$num=mysql_num_rows($home);
$i=0;
while ($i < $num) {
$f1=mysql_result($home,$i,"code"); //**
$i++;
}
switch($_GET['page']) {
case '#home' : $page = $f1; break; //**
}
echo $page;
如何在MySQL数据库的列中为每个条目标记星号的行上创建字符串和变量?
答案 0 :(得分:1)
我不完全确定数据库中的“变量”和“字符串”是什么意思,但这就是我对此的看法。请注意,我使用的是PDO,因为mysql_*
函数已弃用。
// this is how you connect with PDO
$dbh = new PDO('mysql:dbname=yourdbname;host=yourhost','youruser','yourpassword');
// you can name the column from the database itself. This is much faster
// also the ? is a placeholder. We'll pass the value on execute()
// this prevents SQL Injection attacks.
$sth = $dbh->prepare("SELECT code FROM data WHERE callsign=?");
// use try { } catch { } to detect errors
try {
$sth->execute( array($_GET['page']) );
}
catch(PDOException $e) {
die( $e->getMessage() );
}
// now you can fetch(). This returns the first row as an array. list() names the only variable in it
list($code) = $sth->fetch(PDO::FETCH_NUM);
$sth->closeCursor(); // close the cursor or you'll have problems reusing the db handle
print $code; // output is a string