如果$result只有一行,则将其转换为会话。

4

我想从表“account”中查询一行数据。由于MYSQLI使用方面我有点混乱,因此需要一些建议。我该如何做到这一点?

$link = mysqli_connect("localhost","root","","database") or die("Error " . mysqli_error($link));

$query = "SELECT * FROM account WHERE username='".$user."' AND password='".$passcode."' LIMIT 1";
$result = $link->query($query) or die("Error " . mysqli_error($link));
$numrow = $result->num_rows;
$res = $result->fetch_assoc();

查询后我想将数据复制到一个会话中,我是这样做的:

    session_start();  
    $tableau = array($res['cod_acc'],$res['username'],$res['password']); 
    $_SESSION['tableau'] = $tableau;

在这之后,我该如何打印数据?
    $tableau = $_SESSION['tableau']; 
    echo "$tableau['username']";

1
你遇到了什么问题?有出现任何错误信息吗?哪些功能无法正常工作? - Marco Aurélio Deleu
那应该按预期工作吗?你收到了什么错误信息? - Atilla Arda Açıkgöz
你为什么要混合使用过程式编程和面向对象编程呢? - devpro
2个回答

2

从你的问题中:

我怎样才能打印数据?

首先,您需要在代码中添加error_reporting()

error_reporting(E_ALL);

您正在使用数组为$_SESSION保存值:

$tableau = array($res['cod_acc'],$res['username'],$res['password']); 
$_SESSION['tableau'] = $tableau;

如果您查看会话数组,它不是一个关联数组。因此,您无法像这样获得结果:
$tableau = $_SESSION['tableau']; 
echo $tableau['username'];

解决方案:

您可以从会话数组中获取用户名,如:

echo $tableau[1]; // username on second index.

解决方案2:

如果您想使用关联索引,则需要使用关联数组,例如:

$tableau = array(
"cod_acc"=>$res['cod_acc'],
"username"=>$res['username']); 
$_SESSION['tableau'] = $tableau;

现在您可以按照需要使用。请注意,我正在从会话中删除密码字段,因为我认为它不必要。
附注:
我不知道为什么将过程化和面向对象的风格混合在一起。

0
问题出在其他行的代码中,对于这篇文章我很抱歉。但还是谢谢大家。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接