[英]How to mysql_query in cycle until result?
I have a table of nested product categories. 我有一张嵌套的产品类别表。 I want to get data from field custom_inserts_ru
and if it's empty - go to top (parent category) and check again. 我想从字段custom_inserts_ru
获取数据,如果它为空,请转到顶部(父类别)并再次检查。
$mycat = 1146;
$result = mysql_query("SELECT categoryID, parent, custom_inserts_ru FROM SC_categories WHERE categoryID=$mycat");
while($row = mysql_fetch_row($result)) {
if($row[2]==''){
$mycat = $row[1];
} else {
echo "$row[1] <pre>$row[2]</pre>";
}
}
I try this, but don't work( 我尝试了这个,但是不起作用(
I would do it like this 我会这样
function get_inserts ($db, $id) {
$base_sql = "SELECT c.categoryID,
c.parent,
IFNULL(c.custom_inserts_ru, p.custom_inserts_ru) custom_inserts_ru,
p.parent parent_parent
FROM SC_categories c LEFT JOIN
SC_categories p ON c.parent = p.categoryID
WHERE c.categoryID=";
$inserts = "";
do {
$result = mysql_query ($base_sql . $id, $db);
if (!$result) break;
$row = mysql_fetch_assoc($result);
$inserts = $row['custom_inserts_ru'];
$id = $row['parent_parent'];
} while (strlen($inserts) == 0 && $id);
if($result) {
mysql_free_result ($result);
}
return $inserts;
}
To lessen the number of subsequent queries for a deep tree of categories a self join is introduced which fetches value of custom_inserts_ru
either from current category or from its immediate parent in one select. 为了减少对一棵深树类别的后续查询的数量,引入了一种自我custom_inserts_ru
,该custom_inserts_ru
可以一次选择从当前类别或其直接父项中获取custom_inserts_ru的值。
To use it 使用它
$mycat = 1146;
$db = mysql_connect(...);
if (!$db) {
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('test', $db);
if (!$db_selected) {
die ('Unable to select database : ' . mysql_error());
}
$inserts = get_inserts($db, $mycat);
echo "custom_inserts_ru for Id $currentID is '$inserts'";
mysql_close($db);
Since mysql_*
extension is deprecated , you better switch to PDO or MySQLi and use prepared statements . 由于不建议使用 mysql_*
扩展名,因此最好切换到PDO或MySQLi并使用准备好的语句 。
无论如何,您真的根本没有搜索过任何东西,就像最基本的东西一样:
while ($row = mysql_fetch_row($result)) {
//In a cycle
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.