使用好的SQL查询而不是PHP代码

时间:2016-08-12 17:11:59

标签: php mysql sql mysqli

我有一个页面需要很长时间才能加载,我几乎可以肯定这是由于太多的sql请求(由于我糟糕的SQL技能导致的AKA)。无论如何将这3个查询加入一个?

我想用这个查询做的是尝试从cardapios中选择一个特定的id,如果有任何东西(如果$ num_rows> 0),我唯一想做的就是选择那个id。如果那里什么都没有,那么我想插入一些东西然后选择它的id。

    $query = "SELECT id FROM cardapios WHERE nome='$nome'";
    $sql = mysqli_query($con,$query);
    $num_rows = mysqli_num_rows($sql);
    if ($num_rows > 0){
            while ($row = mysqli_fetch_array($sql)){
                $_SESSION['id_cardapio'] = $row['id'];
      $num_rows = 0;
    }}else{
            $query = "INSERT INTO cardapios (nome, kcal, semana)
            VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
            $sql = mysqli_query($con,$query);

            $query = "SELECT id FROM cardapios WHERE nome='$nome' ";
            $sql = mysqli_query($con, $query);
            while ($row = mysqli_fetch_array($sql)){
                $_SESSION['id_cardapio'] = $row['id'];
            }
      }

我试图把所有这些都放在一个查询中,但无处可去。反正只使用一个查询来完成所有这些吗?

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以通过获取mysqli_insert_id($con);来替换上一个查询,因为插入后已经有插入ID

$query = "SELECT id FROM cardapios WHERE nome='$nome'";
$sql = mysqli_query($con,$query);
$num_rows = mysqli_num_rows($sql);
if ($num_rows > 0){
    while ($row = mysqli_fetch_array($sql)){
        $_SESSION['id_cardapio'] = $row['id'];
        $num_rows = 0;
    }
}else{
    $query = "INSERT INTO cardapios (nome, kcal, semana)
        VALUES('$nome', '$kcal', '$semana')" or die(mysqli_error($con));
        $sql = mysqli_query($con,$query);

        if ( $sql !== false) {    // did insert work
            $_SESSION['id_cardapio'] = mysqli_insert_id($con);
        } else {
            // insert did nto work??
        }
}