获取php中的行数

时间:2015-11-06 19:41:34

标签: php mysql mysqli

我目前正在努力使我的代码安全地从sql注入并且正在练习安全地传递用户输入,但是它似乎已经引起了一些问题。

我想在输入之前检查用户是否已经存在于数据库中,但是在获取执行此操作的行数方面存在问题。后一个插入语句工作正常。

    $Check = $conn->prepare("SELECT * FROM Actor WHERE SurName = ? AND FirstName = ?");
    $Check->bind_param('ss',$SurName ,$FirstName);

    $Check->execute();

    if($Check->num_rows == 0)
    {

        //-----------------Change String To Date----------//
        $dob = str_replace('/', '-', $dob);
        $DOB= date("Y-m-d", strtotime($dob));
        //----------------------Insert SQL----------------//
        $insert = $conn->prepare("INSERT INTO Actor(SurName, FirstName, Gender, DOB) VALUES (?,?,?,?)");
        $insert->bind_param('ssss',$SurName ,$FirstName, $Gender, $DOB);
        if ($insert->execute())
        {
            $Confirm=$FirstName.' '.$SurName.' has been added to our database<br>';
        }
        else
        {die(mysqli_error($conn));}
        mysqli_close($conn);
        //header( "refresh:5;url=addactor.php" );
    }
    else
    {$CheckErr="Actor Already Exists";}

编辑:我找到了一个解决方案,答案如下,其他人遇到同样的问题。解决方案是获得结果,然后对其进行计数并将其存储在变量中:

    $Check = $conn->prepare("SELECT * FROM Actor WHERE SurName = ? AND FirstName = ?");
    $Check->bind_param('ss',$SurName ,$FirstName);
    $Check->execute();
    $result = $Check->get_result();
    $count = $result->num_rows;
    if($count==0)
    {
        //-----------------Change String To Date----------//
        $dob = str_replace('/', '-', $dob);
        $DOB= date("Y-m-d", strtotime($dob));
        //----------------------Insert SQL----------------//
        $insert = $conn->prepare("INSERT INTO Actor(SurName, FirstName, Gender, DOB) VALUES (?,?,?,?)");
        $insert->bind_param('ssss',$SurName ,$FirstName, $Gender, $DOB);
        if ($insert->execute())
        {
            $Confirm=$FirstName.' '.$SurName.' has been added to our database<br>';
        }
        else
        {die(mysqli_error($conn));}
        mysqli_close($conn);
        header( "refresh:5;url=addactor.php" );
    }
    else
    {$CheckErr="Actor Already Exists";}

0 个答案:

没有答案