简体   繁体   English

PHP,MYSQL:根据其他两个DB字段的结果打印一个DB字段

[英]PHP, MYSQL: print a DB field based on the result of two other DB fields

I need to select two fields from a table in my database, if the two fields aren't empty then I would need to select a new field from the database and print that out into a div class on my page. 我需要从数据库中的一个表中选择两个字段,如果这两个字段都不为空,则需要从数据库中选择一个新字段并将其打印到页面上的div类中。

I have managed to create a function which should call the two initial fields from my table however cannot figure out how to do the rest. 我已经成功创建了一个函数,该函数应该从表中调用两个初始字段,但是无法弄清楚其余部分。

function returnPlanMoon($val,$con)
{
    return (mysqli_query($con, "SELECT Planet, Moon From MK1 WHERE id = 1"));
}

Eventually I want to be able to check the two initial results and based on the answer select a specific field in the database to be printed. 最终,我希望能够检查两个初始结果,然后根据答案在数据库中选择要打印的特定字段。

Calling mysqli_query returns a mysqli_result object, which has a num_rows property. 调用mysqli_query返回一个mysqli_result对象,该对象具有num_rows属性。 Simply check that $result->num_rows is greater than 0, then run the subsequent query. 只需检查$result->num_rows大于0,然后运行后续查询即可。 Depending on the query being run, you might be able to join the queries and skip the second query. 根据正在运行的查询,您可能可以加入查询并跳过第二个查询。

If a result is returned, but either Planet or Moon is/can be empty (null/empty string), you'll need to pull those values from the result and check each one via mysql_fetch_assoc : 如果返回结果,但是PlanetMoon是/可以为空(空/空字符串),则需要从结果中提取这些值,并通过mysql_fetch_assoc检查每个值:

if(mysql_num_rows($result) > 0){
    $row = mysql_fetch_assoc($result);
    if(!empty($row['Planet'] and !empty($row['Moon'])){
     //run query here, grab Planet and Moon from $row:
     //mysqli_query($conn, "select foo from bar where Planet={$row['Planet']} and Moon={$row['Moon']}");
    }
}
function returnPlanMoon($val,$con){

    $result (mysqli_query($con, "SELECT Planet, Moon From MK1 WHERE id = $val"));

    $num_rows = mysql_num_rows($result);

    if($num_rows > 0){
       // select a new field from the database and print that out into a div class on my page.
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM