douweida2878 2014-12-19 20:12
浏览 46
已采纳

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

I've created a script to receive all rows added to sql in specific time and set variables getting values from specific columns in each new record (row). This is what i did:

<?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.
");
mysql_close($connection);
#}
?>

But with this code, I will only set the variables with the values from last row. What I plan is to set like: $variable1, $variable2, $variable3, $variableX. Where $variableX is the number of rows added (that I've received in array format).

Could you please give me some help? Im newbie in php coding, but believe me, I've really tried hard and also searched in google and in stackoverflow's database before ask it here.

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • douquqiang1513 2014-12-19 20:21
    关注

    With this:

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

    You are overwriting $email, $name, and $phone for each record. You can either collect them in separate arrays like this:

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

    Or Create one big array with the data for each store:

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

    Alternatively, you can put your print_r() inside the loop like this:

    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.
    ");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?