Mysqli DELETE QUERY在PHP脚本中不起作用

时间:2012-04-14 11:31:11

标签: php database mysqli

我使用以下代码从表中删除条目我想要做的是检查是否有任何值从表中删除。如果删除一个值,脚本应该打印成功,否则为false。这就是我的意思到目前为止已经实现了。请帮忙

<?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();
    }

    }
    ?>

2 个答案:

答案 0 :(得分:9)

您删除的内容是affected_rows http://www.php.net/manual/en/mysqli.affected-rows.php

需要替换的内容

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();
}

工作代码

$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 );
    }
}

你应该有一个工作输出

答案 1 :(得分:-1)

如何使用异常。我也稍微更改了代码。

<?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();
    }
?>