从特定时间添加的 MySQL 获取信息


Get info from MySQL added in specific time

我创建了一个脚本来接收在特定时间内添加到sql的所有行,并设置变量从每个新记录(行(中的特定列中获取值。这是我所做的:

<?php
header('Content-type: text/html; charset=utf-8');
$host='localhost';
$user='username';
$password='password';
$dbname='racheaqui';
$connection=mysql_connect('localhost:/var/run/mysqld/mysqld.sock',$user,$password) or die ("connection failed");
mysql_select_db($dbname, $connection);
$query = "SELECT * FROM store WHERE date >= NOW() - INTERVAL 20 MINUTE;";
$result=mysql_query($query, $conexao);
if ($result){
while($row = mysql_fetch_assoc($result)){
$email=$row['email_contact'];
$name=$row['name'];
$phone=$row['phone_contact'];
}
}
#if (!empty($name)) {
print_r("The user ".$name." with phone ".$phone." and e-mail: ".$email." has created an account in the system.'n");
mysql_close($connection);
#}
?>

但是使用此代码,我将仅使用最后一行的值设置变量。我计划设置为:$variable 1、$variable 2、$variable 3、$variableX。其中$variableX是添加的行数(我以数组格式收到的(。

你能给我一些帮助吗?我是php编码的新手,但相信我,我真的很努力,并且在在这里询问之前还在谷歌和stackoverflow的数据库中进行了搜索。

提前谢谢。

有了这个:

while($row = mysql_fetch_assoc($result)){
    $email=$row['email_contact'];
    $name=$row['name'];
    $phone=$row['phone_contact'];
}

您将覆盖每条记录的$email$name$phone。您可以将它们收集在单独的数组中,如下所示:

$emails = array();
$names = array();
$phones = array();
while($row = mysql_fetch_assoc($result)){
    $emails[]=$row['email_contact'];
    $names[]=$row['name'];
    $phones[]=$row['phone_contact'];
}

或者为每个商店创建一个包含数据的大数组:

$data = array();
while($row = mysql_fetch_assoc($result)){
    $data[] = array(
        'email' => $row['email_contact'],
        'name' => $row['name'],
        'phone' => $row['phone_contact']
    );
}

或者,您可以将print_r()放入循环中,如下所示:

while($row = mysql_fetch_assoc($result)){
    $email=$row['email_contact'];
    $name=$row['name'];
    $phone=$row['phone_contact'];
    print_r("The user ".$name." with phone ".$phone." and e-mail: ".$email." has created an account in the system.'n");
}

每次通过 while 循环时都会覆盖变量。尝试将 print 语句放在 while 循环中,例如 打印$email .">
"; 打印$name .">
"; 打印$phone .">
";而不是使用print_r

您可能希望在循环中放置一个计数器并打印它。

如果您

想知道所选行数,请使用mysql_num_rows

if ($result)
{
    $nr_rows = mysql_num_rows($result);
    while($row = mysql_fetch_assoc($result))
    {
        $email=$row['email_contact'];
        $name=$row['name'];
        $phone=$row['phone_contact'];
        print "The user ".$name." with phone ".$phone." and e-mail: ".$email." has created an account in the system.'n";
    }
    print "Accounts created the last 20 minutes: ".$nr_rows; 
}