我正在运行一个sql查询,它使用内连接从两个表中提取id,catid,name,subof。
select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name
现在这会导致我需要的一切,但我需要遍历结果并对subof值执行另一个sql查询(这是一个值,值是shop_cat的ID号)。我需要提取子值#的catname,然后将结果/数组字段subof更新为cat的名称。
因此,如果原始查询为subof提供了值15,它将从shop.cat中选择catname,其中id ='15'我将从该查询中获取catname,然后为每个值更新subof = catname在具有子值的原始结果中。
编辑3/23/13 12:30 pm MST:使用Opeyemi编写的更多代码来解释我需要的更多内容。我不知道怎么解释它......
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
$getname = mysql_query("select catname from shop_cat where id='$subof'");
$rowname = mysql_fetch_assoc($getname);
//code to update array to change value of $subof to new $rowname['catname']
}
数据库查询运行,获取我的值。
然后我需要运行某种循环,它将遍历从查询中获取的每个PHP结果。此循环将获取子值(这是一个整数ID号),然后运行查询以获取该整数值的值catname。然后循环将更新当前结果并将subof值从整数更改为从循环中的DB中提取的catname。
我不需要随时更新数据库,我需要从第一个查询更新结果/数组。
答案 0 :(得分:1)
您需要做的是将结果集存储在数组中并在数组中替换。
$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
$dataset = array();
// Store result in an array
while($assoc = mysql_fetch_assoc($r)) {
$dataset[] = $assoc;
}
// Update array
foreach($dataset as $data) {
$getname = mysql_query("select catname from shop_cat where id='{$data['subof']}'");
$rowname = mysql_fetch_assoc($getname);
// replace data
replace_dataset($data['subof'], $rowname);
}
function replace_dataset($key, $newname) {
global $dataset;
foreach($dataset as $k => $data) {
if ($data['id'] == $key)
$dataset[$k]['subof'] = $newname;
}
}
答案 1 :(得分:0)
您是否在PHP中询问如何执行此操作?如果您正在寻找如何在PHP中循环结果,那么就像这个
一样简单$q = "select shop.id, shop.catid, shop.name, shop_cat.catname, shop_cat.subof from shop inner join shop_cat on shop.catid = shop_cat.id where shop.active='1' order by shop_cat.catname, shop.name";
$r = mysql_query();
while(list($shopid, $catid, $name, $catname, $subof) = mysql_fetch_array($r)) {
// the values from the query are assigned to the variables
// $shopid, $catid, $name, $catname, $subof in that order already
mysql_query("update shop_cat set subof=catname where id='$subof'");
// My interpretation of your query can be wrong though
// But you should get the idea
}
答案 2 :(得分:0)
您可以使用mysql_fetch_assoc()或mysql_fetch_array()或mysql_fetch_row()函数来获取行,并可以将循环概念放在其上。
之后你可以使用mysql_fetch_field()从中获取字段subof和id。
并在此之后更新数据库
您可以查看以下链接
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-fetch-assoc.php
http://www.php.net/manual/en/function.mysql-fetch-field.php
我希望你能有所了解。