【问题标题】:Create strings from MySQL entries从 MySQL 条目创建字符串
【发布时间】:2023-04-04 02:09:01
【问题描述】:

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

【问题讨论】:

  • 我觉得应该是$f1=mysql_result($home,$i);..
  • 你的问题不是很清楚。假设此代码有效,它似乎会返回一个字符串。
  • @mithunsatheesh - 我认为他正在寻找一个名为 code 的字段,但你是对的,我怀疑这会起作用。第三个参数应该是数字。 while 循环也没用
  • 对,数据库上的字段叫“code”
  • @Cfreak:对不起老兄。你是对的。但第三个参数不是绝对必要的。

标签: php mysql database content-management-system


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-19
    • 2016-04-29
    • 2019-09-02
    • 2021-07-08
    • 2012-11-27
    • 1970-01-01
    相关资源
    最近更新 更多