简体   繁体   中英

How to check whether mysql update query is successful or not?

function insertNewBidPrice($code, $newBidPrice)
{
  global $conn;
  $sql = "update auctionitem set highestbid=$newBidPrice where code=$code";
  //echo $sql;
  if($conn->query($sql))
  {
    return 1;
  }
  else
  {
    require 0;
  }
}

I have this php fuction that results 0 all time although update query successfully update the table.

I use PDO.

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Create a statement object first, using prepare.

$stmt = $conn->prepare($sql);
$worked = $stmt->execute();
if ($worked == TRUE) {
    //I did stuff
} else {
    // nope
}
function insertNewBidPrice($code, $newBidPrice) {
    global $conn;
    // write your query
    $sql = "UPDATE auctionitem SET highestbid='$newBidPrice' WHERE code='$code'";

    // run the query
    $result = $conn->query($sql);

    // check the result of the query
    if ($result == true) {
        // it was a success
        return 1;
    } else {
        return 0;
    }
}

global $conn;
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    // it worked
}

Here you go this should do the trick. I noticed you say "require 0" in your if else statement it needs to be a return. Other then that i'm not sure on your problem but there are 2 possibilities i can think of.

  1. Your $conn variable is invalid. Check it has the correct credentials, see the $conn->connect_error line, it is in the code i wrote but also here: http://php.net/manual/en/mysqli.connect-error.php .
  2. Possibly the query incorrect. Personally i format everything with capitals ect. as my text editor colors it when i do that and it is easy for me to see what is what. Also there were no quotes surrounding the variables in your SQL statement, this is fine if it is an integer but if you are accidentally passing a string it will fail.

Also check that you have selected the correct table ect. in your SQL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM