-2

我正在尝试在我的简单 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 数据库列中的每个条目在标有星号的行上创建字符串和变量?

4

1 回答 1

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
于 2012-07-04T05:24:50.740 回答