美好的一天,我这里有我的代码,以便将出生日期的年龄存储在我的数据库中。
$connect=mysql_connect("localhost","root","");
mysql_select_db("mydb",$connect);
$query = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data";
$result = mysql_query($query);
$values = mysql_fetch_assoc($result);
$age = $values['age'];
$query="select * from data";
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$age."</td>";
echo "</tr>";
}
echo "</table>";
}
所有数据都是获取但唯一的问题是第一行的年龄与我的其余数据相同。我的代码有什么问题?有人帮忙,谢谢你。
答案 0 :(得分:0)
您正在从数值数组打印预取的年龄 而是从当前行读取并用于显示。
更改您的SQL查询,如下所示:
$query = "select id, lname, fname,
date_format(now(), '%Y') - date_format(dob, '%Y')
- ( date_format(now(), '00-%m-%d')
< date_format(dob, '00-%m-%d'))
as age
from data";
更改:
echo "<td>".$age."</td>";
致:
echo "<td>".$row['age']."</td>";
答案 1 :(得分:0)
问题是你是在一次性获取年龄,在while循环中获取dob然后计算年龄并在while循环中打印年龄。
答案 2 :(得分:0)
考虑到您的年龄公式是正确的,请尝试此查询。
// query will give all records and age for each record.
$query="SELECT a.*, (SELECT TIMESTAMPDIFF(YEAR,dob,NOW()) FROM data AS b WHERE a.id = b.id) AS age FROM data AS a";
// rather than getting two result sets, you have age in the same record now, access it as a field.
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['lname']."</td>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['age']."</td>"; // get age from db results
echo "</tr>";
}
echo "</table>";
}
答案 3 :(得分:0)
您正在老化一次并将其用于其余数据。 尝试这样的事情:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db("mydb", $connect);
$query = "select * from data";
$result = mysql_query($query);
if (mysql_num_rows($result) > 0) {
echo "<table align='center' border='1'>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>Last Name</th>";
echo "<th>First Name</th>";
echo "<th>Age</th>";
echo "</tr>";
while ($row = mysql_fetch_array($result)) {
$query1 = "select date_format(now(), '%Y') - date_format(dob, '%Y') - (date_format(now(), '00-%m-%d') < date_format(dob, '00-%m-%d'))
as age from data where id = $row[id]";
$result1 = mysql_query($query);
$values1 = mysql_fetch_assoc($result);
$age = $values1['age'];
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $age . "</td>";
echo "</tr>";
}
echo "</table>";
}