0

I am trying to execute the following.

public function result_multi($sql) {

    try {
        mysqli_multi_query($this->db_connection,$sql);
        $result=mysqli_store_result($this->db_connection);
        $row=mysqli_fetch_row($result);
    }

$b=new DB;
$sql="INSERT INTO payout (mid, type, datetime) VALUES ('0','BC', 
NOW());SELECT LAST_INSERT_ID();";
$b->result_multi($sql);

$row returns NULL and $result return FALSE, however when I execute the SQL query in phpmyadmin it works.

GMB
  • 216,147
  • 25
  • 84
  • 135
the_big_blackbox
  • 1,056
  • 2
  • 15
  • 35
  • 2
    Your code looks invalid. I don't think you can have a try block without a catch and/or finally block (what would be the point?) – GordonM Jan 17 '19 at 14:30
  • Here's a comprehensive post: https://stackoverflow.com/a/22469722/2943403 but honestly why not only INSERT then use php to grab the last id? http://php.net/manual/en/mysqli.insert-id.php – mickmackusa Jan 17 '19 at 14:50

2 Answers2

3

When it comes to fetching the results of a multi query, the mysqli_multi_query documentation states :

To retrieve the resultset from the first query you can use mysqli_use_result() or mysqli_store_result(). All subsequent query results can be processed using mysqli_more_results() and mysqli_next_result().

So you would need to call mysqli_next_result once to access the results of the second query, and then mysqli_store_result/mysqli_fetch_row to fetch the id.

But in your use case, it seems like a simpler way to proceed is to use mysqli_insert_id method, like :

my $conn = $this->db_connection;
$sql = "INSERT INTO payout (mid, type, datetime) VALUES ('0','BC', NOW())";
if (mysqli_query($conn, $sql)) {
    $last_id = mysqli_insert_id($conn);
    echo "Record inserted with ID " . $last_id;
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

PS : you should also check for errors after opening the connection to the database.

GMB
  • 216,147
  • 25
  • 84
  • 135
-2

I need more code for this, because you used the multi sql so must have more query.

Try this code if only one query sql :

public function result($sql) {

    try {
        mysqli_query($this->db_connection,$sql);
        $result=mysqli_store_result($this->db_connection);
        $row=mysqli_fetch_row($result);
    }

$b=new DB;
$sql="INSERT INTO payout (mid, type, datetime) VALUES ('0','BC', 
NOW());SELECT LAST_INSERT_ID();";
$b->result($sql);
Baby Corp
  • 1
  • 3