How to get the result of an insert query - php

I want to get the result of an insert query like this :
$query = "INSERT INTO articles (Title,Description) VALUES ('{$title}','{$description}')";
$result = mysqli_query($connection, $query);
When I insert this article , I want his ID to use it in an other table ! the $result gives a true or false !

You can get the ID of the inserted row by calling the function mysqli_insert_id() directly after your mysqli_query().
$query = "INSERT INTO articles (Title,Description) VALUES ('{$title}','{$description}')";
$result = mysqli_query($connection, $query);
$id = mysqli_insert_id($connection);

use mysqli_insert_id ()
$insertId = mysqli_insert_id ( $connection );

Use this it return the value of your table fiele which is (peimary key) in this table
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());

Related

updating the data using implode in php

please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}

PHP to SqlServer, Getting the last inserted identity

I'm trying to get the last inserted identity in my Orders table in order to insert the same ID into a linked OrderItems table, for each item in my cart array. My Orders table "orderID" is my identity variable, but when I try to pull the most recently inserted value, the result is "null." The original INSERT query into the Orders table is successful, but for some reason the "SELECT ##IDENTITY" query is not.
PHP Code
$ordersquery= "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('{$phonenumber}', '{$time}', 'online')";
echo $ordersquery."\n";
$result= mssql_query($ordersquery, $db);
var_dump($result);
echo mssql_get_last_message();
$idquery= "SELECT ##IDENTITY as id";
$result= mssql_query($idquery, $db);
$id= mssql_fetch_array($result)[$id];
var_dump($id);
foreach ($cart as $item) {
$itemID= $item['id'];
$quantity= $item['quantity'];
$orderitemsquery= "INSERT INTO OrderItems VALUES ('{$id}' '{$itemID}', '{$quantity}')";
if ($resultitems= mssql_query($orderitemsquery, $db)){
echo $orderitemsquery;
}
}
Result
INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES ('(433) 943-4334', '2015-05-10 14:46:40', 'online')
boolean true
The statement has been terminated.
null
boolean false
Oracle doesn`t have autoincrement. The best you can do, is to get the id first, then do the insert. You get the id like this:
$statement = oci_parse(OCI_CONN, "Select my_seq.nextval from dual");
if (oci_execute($statement)) {
$row = oci_fetch_assoc($statement);
$id = $row['NEXTVAL'];
}
$query = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$resource=sqlsrv_query($conn, $query, $arrParams);
sqlsrv_next_result($resource); //note this line!!
sqlsrv_fetch($resource);
echo sqlsrv_get_field($resource, 0);
Or - if you prefer "mssql_" extension functions:
$sql = "INSERT INTO Orders (customerID, orderDate, OrderOrigin) VALUES (?,?,?); SELECT SCOPE_IDENTITY()";
$results = mssql_fetch_assoc(mssql_query($sql));
$lastid=$results[0];
SCOPE_IDENTITY is generally better because ##IDENTITY is across scopes - it's the last identity inserted into ANY table in the current session, so you better be careful with ##IDENTITY - you can get a value from a trigger or something.

Array can not be displayed

I have a code
$hasil = "INSERT INTO pendaftaran VALUES ('$no_ai','$tgl_daftar','$kode_dokter','$kode_pasien','$petugas_jaga','$bayar','$status_ambil','$catatan')";
$sql = mysql_query($hasil);
foreach($_POST['cek'] as $selected){
foreach($_POST['cek'] as $selek){
$res = mysql_query("SELECT kode_cek FROM master_cek where kode_item='$selected'");
while($koko=mysql_fetch_array($res)){
print_r($koko);
$result = "INSERT INTO detail_daftar VALUES ('',$no_ai','$res','0','','','$selected')";
$sql = mysql_query($result);
print_r($result);
}
}
}
The Result is..
Resource id #5 INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')Resource id #5INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')Resource id #5INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')
I am very confused with the resource id. Please help me thank you :)
It because when query is executed using PHP MySql driver it gives you resource id from where you need to fetch actual result.
If you need to get last insert id then you will have to make one more function call
print_r(mysql_insert_id());
foreach($_POST['cek'] as $selected){
foreach($_POST['cek'] as $selek){
$res = mysql_query("SELECT kode_cek FROM master_cek where kode_item='$selected'");
while($koko=mysql_fetch_array($res)){
print_r($koko);
$result = "INSERT INTO detail_daftar VALUES ('',$no_ai','$koko['kode_cek']','0','','','$selected')";
$sql = mysql_query($result);
print_r($result);
}
}
}
You are trying to insert $res change that to $koko['kode_cek']
Insert query doesn't return array. To get inserted id of executed query you have to call last inserted id function which will return you Id of last inserted record in DB.
Below function will help to get ID of inserted record.
`mysql_insert_id();`

How do I reference the row I had just inserted into a MySQL table?

I have this function in a Code Igniter model that creates a new "video."
// Creates a new video.
public function newVideo($title, $description) {
$this->db->query("INSERT INTO videos VALUES (NULL, '$title', '$description')");
return // id of this new row
}
How do I obtain the ID of this new row in my MySQL table? I could get the last row and add 1, but there could be concurrency bugs I believe.
Very simple answer doesn't really need more than 30 chars does it?
$this->db->insert_id();
maybe you need something like this
$this->db->insert_id();
Try something like that :
$lastID = -1; //That's where it'll be stored
$query = "SELECT LAST_INSERT_ID()";
$result = mysql_query($query);
if ($result)
{
$row = mysql_fetch_row($result);
$lastID = $row[0];
}
Code for an insert is:
$sql = "INSERT INTO videos (title) VALUES(NULL, '$title', '$description')";
$this->db->query($sql);
More information on queries available at: http://codeigniter.com/user_guide/database/queries.html
Another workaround is that you can have a look into videos table in your database, and make you video id as autonumber, this will automatically generate an id for your video and then you can try this:
//on your model
$sql = "INSERT INTO videos (title,description) VALUES('$title', '$description')";
$this->db->query($sql);
//retrieve new video id
$this->db->insert_id()

Get a column value (like id) after mysql INSERT

Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.

Categories