开发者

Can i make this simpler?

开发者 https://www.devze.com 2023-01-18 13:54 出处:网络
Hey, im new to PHP (started last week) ive got 10 lines of info in a SQLDB im doing the same thing to all 10:

Hey, im new to PHP (started last week) ive got 10 lines of info in a SQLDB im doing the same thing to all 10:

$db_line1 = mysql_query("SELECT * FROM messages WHERE message_id='1'");
$line1 = mysql_fetch_array($db_line1);
unset ($line1['0']);
unset ($line1['1']);
unset ($line1['2']);

$db_line2 = mysql_query("SELECT * FROM m开发者_高级运维essages WHERE message_id='2'");
$line2 = mysql_fetch_array($db_line2);
unset ($line2['0']);
unset ($line2['1']);
unset ($line2['2']);

Etc. etc. all the way to $line10, could i use something like the "foreach" function?


$query = mysql_query("SELECT * FORM messages");
while($result = mysql_fetch_assoc($query))
{
  echo "<pre>";
  print_r($result);
  echo "</pre>";
}
unset($result);


Answering to the comment ("can I get them in their own arrays"):

$query = mysql_query("SELECT * FORM messages") or die(mysql_error());
$messages = array();
while($result = mysql_fetch_assoc($query))
{
  $messages[] = $result;
}
unset($result);

You can then iterate over the $messages.


EDIT following author's comment

Take all rows at once

    $db_line = mysql_query("SELECT * FROM messages WHERE message_id >= '1'" .
                           " AND message_id <='10'");

    $rows = array();

    while ($line = mysql_fetch_assoc($db_line))
    {
       $rows[$line['message_id']] = $line;
    }

This way you have an array of rows (ie an array of arrays).

To get the row for message_id 3, just do

   $row = $rows[3];

and to access the (for instance) name column,

   $row['name']

or

   $rows[3]['name']


You may use dynamically created variables in php:

    for ($i = 0; $i < 3; $i++){
        unset(${'line'.$i});
    }

EDIT: How it works (example):

$var1 = "hel";
$var2 = "lo";
$hello = "xxx";

echo ${$var1.$var2};  // outputs "xxx"

Using ${'xyz'.$variable} will give you the variable with name 'xyz'.$variable. Notice that "'xyz'.$variable" gets determined first.


$db_lines = mysql_query("SELECT * FROM messages");
while ($line = mysql_fetch_array($db_lines))
{
    unset ($line['0']);
    unset ($line['1']);
    unset ($line['2']);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号