1

below is my php code, $db is connection to db

<?php

if (! hasEmpty([$_POST['loc-city']])) {
    $city = htmlspecialchars_decode($_POST['loc-city']);
    $addr = htmlspecialchars_decode($_POST['loc-address']);
    $prov = htmlspecialchars_decode($_POST['loc-province']);
    $pos = htmlspecialchars_decode($_POST['loc-poscode']);

    $houseID = mysqli_insert_id($db);

    $sql = "INSERT INTO house (houseID, username, houseStatus) VALUES ('".$houseID."', '".$_SESSION['login_user']."','0')";
    $sql2 = "INSERT INTO house_loc (houseID, city, address, province, postalCode) VALUES ('".$houseID."',?,?,?,?)";

    $query = $db->prepare($sql);
    $query2 = $db->prepare($sql2);
    $query2->bind_param('ssss',$city,$addr,$prov,$pos);

    if (!$query->execute()) {
      echo '{"status":"error", "errorMsg" : "Error!"}';
      exit;
    }
    if (!$query2->execute()) {
      echo '{"status":"error", "errorMsg" : "Error!"}';
      exit;
    }

    echo '{"status":"success"}';
?>

I am having issue with inserting both statements to the database, I tried changing $houseID directly to an int and it works, so I think the problem occured at

$houseID = mysqli_insert_id($db);

as it cannot be used twice?

Chase
  • 93
  • 10
  • 1
    From http://php.net/manual/en/mysqli.insert-id.php: " Returns the auto generated id used in the latest query". But when you are running this command, you haven't yet run any queries, so there will be nothing to return (it defaults to 0 in this case). Is houseID in your database an auto_increment field? If so, you don't need to include it in your SQL INSERT statement. I think maybe you want to retrieve the houseID _after_ the first SQL statement has run, so you can use it in the second one? – ADyson Jul 04 '17 at 10:32
  • Ahh, I did not know that, will try. Thanks! – Chase Jul 04 '17 at 10:41
  • 1
    Yup, got it working. Thanks a lot! – Chase Jul 04 '17 at 10:43

0 Answers0