Mysqli DELETE QUERY not working in PHP script

Im using the following code to remove a record from a table, what I want to do is check if any value has been deleted from the table. If one value is removed, the script should print the success of else false. This is what I have achieved so far. Please, help

<?PHP
    $mysqli = new mysqli("SQLHOST.COM","CLIENT","PASSWORD", "DNAME", 1234);

    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }
    else
    {

    printf("cONN Sucees");


    if ($result = $mysqli->query("DELETE FROM ktable WHERE code='value'")) {
        printf("Select returned %d rows.\n", $result->num_rows);


     printf($result->num_rows);
        $result->close();
    }

    }
    ?>
+3
source share
2 answers

what you delete, you need to return affected_rows http://www.php.net/manual/en/mysqli.affected-rows.php

What needs to be replaced

if ($result = $mysqli->query("DELETE FROM ktable WHERE code='value'")) {
    printf("Select returned %d rows.\n", $result->num_rows);


    printf($result->num_rows);
    $result->close();
}

Working code

$value = ""; // Set To any Value
$mysqli = new mysqli ( "SQLHOST.COM", "CLIENT", "PASSWORD", "DNAME", 1234 );
if ($mysqli->connect_errno) {
    printf ( "Connect failed: %s\n", $mysqli->connect_error );
    exit ();
} else {
    printf ( "cONN Sucees" );
    if ($mysqli->query (sprintf ( "DELETE FROM ktable WHERE code='%s'", mysqli_real_escape_string ( $mysqli, $value ) ) )) {
        printf ( "Affected Rows  %d rows.\n", $mysqli->affected_rows );
    }
}

You must have a working exit

+9
source

How about using execption. I also changed the code a bit.

<?php
$mysqli = new mysqli("SQLHOST.COM", "CLIENT", "PASSWORD", "DNAME", 1234);
$connection = mysqli_connect('SQLHOST', 'CLIENT', 'PASSWORD') or die(mysqli_error());
try {
    $select_db = mysqli_select_db('DBNAME', $connection);
    if (!$select_db) {
        throw new Exception("Could not connect!");
    }
}
catch (exception $e) {
    echo "Error (File: " . getFile() . ", line " . $e->getLine() . "): " . $e->
        getMessage();
}
$query = mysqli_query('DELETE FROM ktable WHERE code="' . $value . ';"');
    if ($query) {

        printf("Select returned %d rows.\n", $result->num_rows);
        printf($result->num_rows);
        mysqli_close();
    }
?>
-1
source

All Articles