0

Can I get multi-rows from a query after implementing? In PHP has LAST_INSERT_ID() function to get just the last row from database and it can't get multi-row . If I have query such as

$sql = "insert into my_table(ID,Column1,Column2) values 
(1,"temp1","temp2"),
(2,"temp3","temp4"),
(3,"temp5","temp6")"

    mysql_query($sql);......

I want to get all ID of this query into an array $data = (1,2,3) . How to implement this?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
AzVoz
  • 369
  • 3
  • 4
  • 8
  • You have to loop through each query, get the id and push that id to an array. – Jay Blanchard Feb 22 '16 at 18:40
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Feb 22 '16 at 18:41
  • you can't. if you want the individual ids, then you have to do individual inserts. last_insert_id() only works on the **LAST** individidual id, and doesn't return a set of ids from a multi-insert. – Marc B Feb 22 '16 at 18:42
  • Where is the data coming from? - you're asking to get something you're putting in to the db. Just capture it before – StudioTime Feb 22 '16 at 18:58
  • just need to use loop. :). First, I think when i use loop, my array is `$data =array(3,3,3)` . I mean, it will push 3 same data from last ID. But i try use loop and it works. Just simple is loop. !! – AzVoz Feb 22 '16 at 19:03

1 Answers1

0

You could use a for loop and store last insert id to a array. Once loop finished you can extract insert id's hope example below helps

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    for ($x = 0; $x <= 10; $x++) {
           $sql = "insert into my_table(ID,Column1,Column2) values  
                 ($x,"temp".$x,"temp".$x)";

           $conn->query($sql);
           $last_id[] = $conn->insert_id;

     } 
    print_r($last_id);
      $conn->close();
Aslan Kaya
  • 514
  • 5
  • 11