变量应该从mysql表中随机获取值,同时属于同一行

时间:2012-03-08 13:18:32

标签: php mysql variables random

我已经制作了一个表单,要求用户输入名字和姓氏,并将其存储在MySQL数据库中 现在在另一个文件中我想随机使用表中的数据库

  <?php
  $con = mysql_connect("localhost","peter","abc123");
  if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

  mysql_select_db("my_db", $con);

  $result = mysql_query("SELECT `column` FROM `table` ORDER BY RAND() LIMIT 1");

  //what should i write here if i want get the randomly selected row data in the following variable
  //$firstname = "   ";
  //$lastname = "  ";


  mysql_close($con);
  ?>

基本上我想要$ firstname $ lastname从MySQL表中随机获取值,同时属于同一行

1 个答案:

答案 0 :(得分:0)

你快到了 - 查询已经正确设置,可以从表中检索1个随机行。您只需指定要检索的列,并在结果上调用mysql_fetch_*()来填充变量:

// ...

// Do the query
$query = "
  SELECT `firstname_col`, `lastname_col`
  FROM `table`
  ORDER BY RAND()
  LIMIT 1
";
$result = mysql_query($query) or trigger_error(mysql_error()." ".$query);

// Fetch the selected row into an associative array
$row = mysql_fetch_assoc($result);

// Assign the variables
$firstname = $row['firstname_col'];
$lastname = $row['lastname_col'];

// ...