【发布时间】:2014-06-01 22:50:29
【问题描述】:
我是 PHP 和 SQL 的新手,这是我第一次在这里发帖,希望我做得对 =)
我需要从数据库中的某个字段中找出数字索引。事情是我还没有完成数据库结构,所以对于这个特定的字段,我想让它自动化,这样我就不必每次添加或删除列时都更改代码。
我还需要它同时具有两种索引类型,这样我就可以在部分代码中按名称调用列,并通过索引来调用其中的自动化部分。
我已经设法通过一个非常丑陋的代码实现了我想要的结果,因为我尝试过的所有 array_search 和 array_keys 由于某种原因没有成功。
这是我工作但丑陋的代码的 sn-p。你有更优雅的解决方案吗?
提前感谢您的回答,以及到目前为止我从阅读其他人的问题中学到的所有知识!
$dadosRes = mysqli_query($con, "SELECT * FROM Alunos WHERE Id=1");
$student = mysqli_fetch_array($dadosRes) or die(mysql_error());
$c = 0; // This block is to find out where the column "cont1" is and assign it to $cont1
$d=array_keys($student);
$cont1=0;
foreach ($student as $a=>$b){
if ($a==='cont1') {
$cont1=$d[$c-1];
}
$c++;
}
for ($i=$cont1; $i<$cont1+12; $i+=3) { // Displays the students contacts, each in up to 3 rows
if ($student[$i]) {
echo "<p><ul><li>".$student[$i]."</li>";
if ($student[$i+1]) echo "<li>".$students[$i+1]."</li>";
if ($student[$i+2]) echo "<li>".$students[$i+2]."</li>";
echo "</ul></p>";
}
}
【问题讨论】:
-
您在寻找
AUTO_INCREMENT专栏吗? -
我认为如果解释一下 $student 包含什么以及 $dadosRes 是什么会更容易。对我来说,这听起来像是你试图解决错误的问题
-
$cont1=$d[$c-1];给出cont1前面的列的名称。 -
编辑问题以包括 $dadosRes,它是来自数据库的资源。我想要实现的是一种更好的方法来提出 $cont1,它不必遍历所有列。还要在问题上说明这一点,谢谢!
-
不要使用
mysql_fetch_array,而是使用mysql_fetch_assoc,它会为您提供按名称的列。