将单个记录从mysql查询保存到变量

时间:2012-06-15 11:52:16

标签: php mysql variables

我有一个表,其中有一行名为ID,我想将该ID保存到我稍后可以在同一个PHP文件中使用的变量。我该怎么做?

<?php
include 'config.php';

// Connect to server and select databse.
mysql_connect("$dbhost", "$dbuser", "$dbpass")or die("cannot connect");
mysql_select_db("$dbname")or die("cannot select DB");

$result = mysql_query("SELECT * auto_matkat");

$row = mysql_fetch_array($result)
  $IND = $row['IND'];
  echo $IND;
  }

mysql_close($con);
?> 

2 个答案:

答案 0 :(得分:1)

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

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT ID FROM IDTable");
$ID="0";

//iterate the result set
while($row = mysql_fetch_array($result)){
  $ID=$row[0] 
  //echo here
  echo "MyID".$ID;
}
  //OR echo here
  //echo "MyID".$ID;

答案 1 :(得分:1)

如果CoDe ADDict的代码对你来说有点复杂,这可能会有点简单:

mysql_connect("$dbhost","$dbuser","$dbpass")or die(mysql_error());
mysql_select_db("$dbname")or die(mysql_error());
     $query="SELECT * FROM auto_matkat";
$result=mysql_query($query)or die(mysql_error());
$num=mysql_numrows($result);
mysql_close();
$i=0;
while($i<$num){
$id[$id]=mysql_result($result,$i,"id");
}
echo $id;

这是一个很棒的网站,适合初学者学习PHP&amp; MySQL连接:http://www.freewebmasterhelp.com/tutorials/phpmysql