Search code examples
phpmysqlsqlhttp-status-code-500

Unable to call php function if sql record exists


I have this code:

<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='you cant know mypassword';

mysql_connect($mysql_host,$mysql_user,$mysql_password);
@mysql_select_db('attempt');



?>


<?php
$sql="IF NOT EXISTS ( SELECT person FROM kid WHERE Subs=45 )
BEGIN
    echo 'hey'
END"

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 


if ($conn->query($sql) === TRUE) {
    echo "Done";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}


?>

The php page is supposed to echo'hey' because no such record exists but the page itself is not even loading at all but returning a HTTP localhost 500 error saying that localhost cannot handle the request.

I know I'm doing something wrong but I'm not sure exactly what.Please help


Solution

  • Okay so delete all and use like that:

    <?php
    
    $mysqli_host = 'localhost';
    $mysqli_user = 'root';
    $mysqli_password = 'yourPassword';
    $mysqli_database = 'yourDatabase';
    
    $mysqli = new mysqli($mysqli_host, $mysqli_user, $mysqli_password, $mysqli_database);
    
    if ($mysqli->connect_errno) {
        die("Connection failed: " . $conn->connect_error);
    }
    
    $query = mysqli_query($mysqli, "SELECT person FROM kid WHERE Subs=45");
    $result = mysqli_num_rows($query);
    
    if($result > 0) {
        echo("Exist");     
    } else {
        echo("Doesn't exist");
    }
    
    ?>