简体   繁体   中英

Update table using mysqli

I wrote a PHP function, that takes two input parameters and updates a database table.

function updateTable($a, $b){

        $query = "UPDATE myTable
                  SET dataUpload=CURDATE(), lastUpdate=NOW()
                  WHERE Code IN(SELECT Code FROM myTable2 WHERE QR = ?) AND aid=?";
        $stmt=$connectiondb->stmt_init();
        if (!($stmt = $connectiondb->prepare($query))) {
          echo "Prepare failed: (" . $connectiondb->errno . ") " . $connectiondb->error;
           $firephp->log("prepare failed in update myTable");
        }
        if (!$stmt->bind_param('si',$a, $b)) {
          echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
          $firephp->log("bind failed in update myTable");
        }
        if (!$stmt->execute()) {
          echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
          $firephp->log("execute failed in update myTable");
        }

        $stmt->free_result();
        $stmt->close();
}

where:

$connectiondb = new mysqli($hostname, $username, $password, $database);

If I call this function, inside PHP code, for example in this way:

updateTable('923TRU234',1100);

it does not work, but if I call the update statement on the MySQL database:

UPDATE myTable
SET dataUpload=CURDATE(), lastUpdate=NOW()
WHERE Code IN(SELECT Code FROM myTable2 WHERE QR = '923TRU234') AND aid=1100

it works!

It doesn't look like you are referring to your connection properly. You refer to $connectiondb as though it is a global, but it looks like you defined it outside of your function. You don't use the command global $connectiondb; inside the function. So, PHP doesn't know about your connection, and treats $connectiondb as undefined.

See this page on variable scopes in PHP for more information about how this works.

Also, if you can shed more light than "it doesn't work," it will be easier to help you troubleshoot. What does happen?

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