Duplicate MYSQL Record with child records - php

I am using the code below to duplicate a event record in my database, problem is I am trying to also duplicate any child records (i.e. event services). I need it to copy all "event services" from the eventservices table as well as update the eventid during copy to the newly copied id record. Any help would be appreciated. Thanks.
Note: The eventservices table has a eventid field which matches the id of the event.
$table = 'events';
$id_field = 'id';
$id = $_GET['eventid'];
DuplicateMySQLRecord($table, $id_field, $id);
function DuplicateMySQLRecord($table, $id_field, $id) {
include_once 'db_connect.php';
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != $id_field) {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);
// return the new id
return $newid;
}

Please use below code.I have not compile this code so test before use.
<?php
include_once 'db_connect.php';
$table = 'events';
$id_field = 'id';
$id = $_GET['eventid'];
DuplicateMySQLRecord($table, $id_field, $id);
function DuplicateMySQLRecord($table, $id_field, $id) {
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$id}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != $id_field) {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE {$id_field}={$newid}";
mysql_query($query);
if($newid) {
$oldid = $id;
copychilds($table, 'eventid', $oldid,$newid);
}
// return the new id
return $newid;
}
function copychilds($table, $id_field, $oldid,$newcopiedid) {
$result = mysql_query("SELECT * FROM {$table} WHERE id={$oldid}");
while($original_child_record = mysql_fetch_assoc($result){
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`id`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != 'id') {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query .= '`'.$id_field.'` = "'.str_replace('"','\"',$newcopiedid).'", ';
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE id={$newid}";
mysql_query($query);
}
}
?>

Ok, I have all of this working with a few tweaks.
Below is my function, everything is working great, however, it only gets the first record and there may be multiple children. Any help appreciated.
function copychilds1($table, $id_field, $oldid,$newcopiedid, $updatedid) {
include_once '../inc/db_connect.php';
// load the original record into an array
$result = mysql_query("SELECT * FROM {$table} WHERE {$id_field}={$oldid}");
$original_record = mysql_fetch_assoc($result);
// insert the new record and get the new auto_increment id
mysql_query("INSERT INTO {$table} (`{$id_field}`) VALUES (NULL)");
$newid = mysql_insert_id();
// generate the query to update the new record with the previous values
$query = "UPDATE {$table} SET ";
foreach ($original_record as $key => $value) {
if ($key != 'id') {
$query .= '`'.$key.'` = "'.str_replace('"','\"',$value).'", ';
}
}
$query = substr($query,0,strlen($query)-2); # lop off the extra trailing comma
$query .= " WHERE id={$newid}";
mysql_query($query);
$finalquery = "UPDATE eventservices SET eventid = {$updatedid} WHERE id = {$newid}";
mysql_query($finalquery);
// return the new id
return $newid;
}

Related

select all records and the rest

here is a simple mysqli query to select specific records from my mysql database:
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
}
The question is:
How can I get (best practices) all the other records, which will not be selected with this query filter?
It can be like
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
$query2 = "select * from 'myTable' WHERE 'bookid' != ".$zeile['ID']."'";
$result2 = $db -> query($query2);
// do something...
}
}
OR
foreach ($getData as $data) { {
$sql = "SELECT * FROM `myTable` WHERE `bookid` = '".$data['ID']."' ";
$result = $db->query( $sql );
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
$query2 = "select * from 'myTable' WHERE 'bookid' != '".$data['ID']."'";
$result2 = $db -> query($query2);
while($zeile2 = $result2-> fetch_object()){
// do something...
}
}
Running successive, more or less identical, queries in a loop is fundamentally a bad way to do things. Create a list of $data['ID'] values you want to work with, then use one query to retrieve all the rows IN that list, and a second query to retrieve everything NOT IN that list:
Important: This code assumes that the values in $getData[]['ID'] can be trusted. i.e. they have been validated before entry to this code, or they come from a trusted source.
// Create a list:
$inList = '('.implode(',', array_column($getData, 'ID')).')';
$sqlIn = "SELECT * FROM `myTable` WHERE `bookid` IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlIn )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}
// Now use the same list to exclude those rows
$sqlOut = "SELECT * FROM `myTable` WHERE `bookid` NOT IN $inList";
// run the query. Check for errors
if (($result = $db->query( $sqlOut )) === false) {
throw new Exception($db->error);
}
while ($zeile = $result->fetch_object()) {
// DO SOMETHING
}

PHP get last insert id in first query and execute it on second query with multi row

I need help. I have a problem using multi query I want to put the last insert id in the next query the problem is it only adds one. Cart_id and qty has a multiple row. Please i need help thanks in advance.
Here is my code:
public function insertOrder($cart_id = null,$qty = null)
{
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = $this->db->con->insert_id;
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Parameters inserting multiple values in each row
if (isset($_POST['cartid']) && $_POST['qty']){
foreach ($_POST["cartid"] AS $key => $item){
$result = $product->insertOrder($_POST['cartid'][$key], $_POST['qty'][$key]);
echo json_encode($result);
}
}
Tried you injecting a sql SELECT query between two insert methods?
public function insertOrder($cart_id = null,$qty = null){
if (isset($cart_id)) {
$query = "INSERT INTO `tblsales`(`user_id`, `status`) VALUES ('23','delivery');";
$last_id = getLastId("tablename");
$query .= "INSERT INTO `tblorders`(`sales_id`,`product_id`, `quantity`) VALUES ($last_id, {$cart_id},{$qty});";
$result = $this->db->con->multi_query($query);
if ($result) {
header("Location :" . $_SERVER['PHP_SELF']);
}
return $result;
}
}
Get last id function:
function getLastId($tablename){
$sql = "SELECT id FROM $tablename ORDER BY id DESC LIMIT 1";
//any necessary method, and $id = get sql result
return $id;
}

PHP Not Executing the SQL Query for Updating User Details

I have 2 tables in the database, artists (username and password) and artistcard (contains info about the artist with one of the columns being artist_id to link to the artists table).
Now I want the users to be able to update the information displayed in the card:
Currently I get firstname, lastname, genre and location from the form that they can submit:
<?php if (isset($_POST['submit'])) { // Form has been submitted.
$genre = trim($_POST['genre']);
$location = trim($_POST['location']);
$firstname = trim($_POST['firstname']);
$lastname = trim($_POST['lastname']);
$artistcard = new Artistcard();
$artistcard->first_name = $firstname;
$artistcard->last_name=$lastname;
$artistcard->genre = $genre;
$artistcard->location = $location;
$artistcard->artist_id = $_SESSION['artist_id'];
$artistcard->update();
}
Now I want the update function to go through the fields where artist_id in the artistcard table matches id in the artist table (or session id). For this I have in the Artistcard class:
public function update() {
global $database;
$attributes = $this->sanitized_attributes();
$attribute_pairs = array();
foreach($attributes as $key => $value) {
$attribute_pairs[]= "{$key}='{$value}'";
}
// - UPDATE table SET key='value', key='value' WHERE condition
$sql = "UPDATE ".self::$table_name." SET ";
$sql .= join(", ", $attribute_pairs);
$sql .= " WHERE artist_id=". $database->escape_value($this->artist_id);
$database->query($sql);
return ($database->affected_rows() == 1) ? true : false;
}
which returns Database Query Failed. I'm guessing the SQL is not correct? I have an almost identical CREATE method, which works fine:
public function create(){
global $database;
$attributes = $this->sanitized_attributes();
$sql = "INSERT INTO ".self::$table_name." (";
$sql .= join(",",array_keys($attributes));
$sql .= ") VALUES ('";
$sql .= join("', '",array_values($attributes));
$sql .= "')";
if ($database->query($sql)) {
$this->id = $database->insert_id();
return true;} else {return false;}
}

insert value to table if row doesnt exist

I have database that hold my data in mysql.
I have already data in my table (call words) and I want to insert new data to this table but before I want to check if this data not already exist.
I have function that insert the data to table but I need sql query that will check if the data not exist?
the colum in my table 'words' are :word , num , hit , instoplist.
I write the code in PHP
Thanks,
this is my code:(insert to table function)
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
Before inserting the data make a select query on a column which is unique as per your requirement like:
$chkExist = "select id from table where col_name = '".$value."'";
$res = $conn->query($chkExist);
// Now check if there is some record in $res than stop the entry otherwise insert it
function insert($myWords)
{
global $conn;
$temp1 = $value['document'];
$temp2 = $value['word'];
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$sql2 "SELECT * FROM words WHERE word = '".$value['word']."' OR num = '".$value['document']."'"; //other data if you want
$resultat=mysql_query($query);
if($resultat==""){
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
}
$sql = rtrim($sql,','); //to remove last comma
if($conn->query($sql)!== TRUE)
{
echo "error". $conn->error;
}
}
$sel="select * from words where word = '$word' AND document = '$document' AND hit = '$hit' AND stopList ='$stopList'";
$qry=mysqli_query($sel);
$num=mysqli_num_rows($qry);
if($num==0){
$sql = "INSERT INTO words (word,num,hit,instoplist) VALUES";
foreach ($myWords as $key => $value) {
$word = $value['word'];
$number = $value['document'];
$hit = $value['hit'];
$stop = $value['stopList'];
$sql .= "('$word', '$number', '$hit','$stop'),";
}
$sql = rtrim($sql,',');
}else{
echo "Already Exist";
}

how to return value of selected id in database php

I insert in the database a csv file. how will i return the id and use it to insert in another table. it always displays array to string conversion errror. is there something wrong with "return"
here is my controller
public function uploadThree(){
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file,"r");
while(($fileop = fgetcsv($handle,1000,",")) !==false)
{
$appname = $fileop[0];
$servname = $fileop[1];
$ciname = $fileop[2];
$servid = $this->some_model->insertBulkServ($servname); //i tried to get the value here then insert below
$appid = $this->some_model->insertBulkSingleApp($appname);//i tried to get the value here then insert below
$this->some_model->insertBulkCI($ciname);
$this->some_model->ASMAP($appid,$servid);
}
if($success == TRUE)
redirect(base_url().'some_controller/uploadPage');
}
MODEL
public function insertBulkServ($service) {
/* Inserts csv file for a service */
$service = $this->db->escape_str($service);
$queryStr = "Select service from appwarehouse.service where service = '$service' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
//in here how do i get the ID how do i return it
}else{
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.service WHERE service='$service' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function insertBulkSingleApp($app_name) {
/* Inserts csv file for an application */
$app_name = $this->db->escape_str($app_name);
$queryStr = "Select * from appwarehouse.application_table where app_name = '$app_name' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
else{
$queryStr = "INSERT INTO appwarehouse.application_table(app_name)
VALUES ('$app_name');";
$query = $this->db->query($queryStr);
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
$row = $query->result();
return $row;
}
}
public function ASMAP($appid,$servid) {
$appid = $this->db->escape_str($appid);
$servid = $this->db->escape_str($servid);
$queryStr = "Select * from appwarehouse.app_service where app_id = '$appid' AND serv_id = '$servid' and VISIBILITY = 'VISIBLE'";
$query = $this->db->query($queryStr);
if($query->num_rows()>0){
return true;
}
else{
$queryStr = "INSERT INTO appwarehouse.app_service(app_id,serv_id)
VALUES ('$appid','$servid');";
$query = $this->db->query($queryStr);
return true;
}
}
What you probably want is:
$this->db->insert_id()
The insert ID number when performing database inserts.
More Info: http://ellislab.com/codeigniter/user-guide/database/helpers.html
You need to do it it is very simple
After the query insert
$queryStr = "INSERT INTO appwarehouse.service(service) VALUES ('$service');";
Instead of select use this
return $this->db->insert_id();
Or if you really need to return the object
$queryStr = "SELECT id FROM appwarehouse.application_table WHERE app_name='$app_name' AND visibility = 'VISIBLE';";
$query = $this->db->query($queryStr);
Return id instead of object
return $query->row()->id;
One more thing to note. insert_id is the last inserted id so you dont have to run select query to get id.
Also use row() to select single record. result() selects multiple records so you will get an array. see here.

Categories