How to copy a row from one mysql table to another - mysql

Please forgive if already answered. I have looked at lots of other questions and none are helping! Basically, I want to copy a single row from one table, to another table. The problem I have struck, is the the id of the row I want to copy, is already in use, in the table I want to copy to. This is what I have at present, it works, until it strikes this problem.
INSERT INTO venues SELECT * FROM submitted_venues WHERE id='9';
It generates the error: Duplicate entry '9' for key 'id'
Is there a way to change the id number on the fly, so that it create an unused new number for the receiving table, or do I have to write a query that names and gets all of the fields for each table. Some thing like the replace statement 0 cases would be good, where 0 creates a new record!!
The 9, is just a number that I used for this example, of course it changes.
EDIT:
I have created a work around for this problem.
//get highest id number of table to copy to
$sql = "SELECT id FROM venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$to_id = $row[ 0 ];
//increase id
$to_id ++;
//get highest id number of table to copy from
$sql = "SELECT id FROM submitted_venues ORDER BY id DESC LIMIT 1";
if( $result = mysqli_query( $mysqli, $sql ) ){
$row = mysqli_fetch_array($result);
$from_id = $row[ 0 ];
//increase id
$from_id ++;
//get highest unused id number
$temp_id = $to_id > $from_id ? $to_id : $from_id;
//update existing record to ensure that its id number will not conflict
$sql = "UPDATE submitted_venues SET id = '$temp_id' WHERE id='$current_venue_id'";
if( $result = mysqli_query( $mysqli, $sql ) ){
$current_venue_id = $temp_id;
//copy record to normal regular venues table
$sql = "INSERT INTO venues SELECT * FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not copy -> " . mysqli_error($mysqli) );
//delete record from temp db table
$sql = "DELETE FROM submitted_venues WHERE id='$current_venue_id'";
if( ! $result = mysqli_query( $mysqli, $sql ) )
die("Could not delete -> " . mysqli_error($mysqli) );
}
}
}

Related

select insert if not exist add or update

im trying to log searches that happen on my website. when someone searches for something i want to first check the database if it has been searched before. if it has add +1 count to the number of searches if it hasnt submit it to the database.
the problem im getting at the moment is anytime you search it updates all logged search terms. i presume becuse i havent set an id. how can i get the id of the search term in the first select query and pass the id as a variable in the second query so it only updates the searchterm associated with that id?
$result = mysql_query("SELECT * FROM wss_search WHERE searchterm ='$trimmed' ");
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE wss_search SET count = count+1 WHERE searchterm = '$trimmed' ");
}
else
{
mysql_query("INSERT INTO wss_search (id, searchterm, count) VALUES ('NULL', '$trimmed', '1') ");
}
any help very much appreciated.
im also aware that i should be using mysqli but the rest of the software hasnt been update to mysqli yet.
Ive got it working using the below code. im new to php could you please tell me why its not secure and what i need to do to make it secure?
$var = $_GET['q'] ;
$trimmed = mysql_secure($var);
$result = mysql_query("SELECT id FROM wss_search WHERE searchterm ='$trimmed' ");
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
}
if( mysql_num_rows($result) > 0) {
mysql_query("UPDATE wss_search SET count = count+1 WHERE id = '$id' and searchterm = '$trimmed' ");
}
else
{
mysql_query("INSERT INTO wss_search (id, searchterm, count) VALUES ('NULL', '$trimmed', '1') ");
}

How to decrement the sequence on an column with auto increment as a constraint, when records are deleted

create table quiz(E_Id INT NOT NULL AUTO_INCREMENT PRIMAR KEY, E_name VARCHAR(255), E_Salary INT)
now whenever i insert data intop table, auto increment works as expected.
Now when i delete the record the sequence of number doesnot get decrement.
Suppose I have a records with Id 1, 2, 3, 4, 5. When i delete the 2 and 3 rd records, the sequence continues from the number 6. I want that if a records is deleted it numbering should get decrement automatically
There is no way for auto-decrementing. But you can use other simple methods.
DROP the field you are auto_incrementing.
ALTER the table to ADD the field again with the same attributes.
Then the list of auto-incrementing will reset.
NOTE: Take care when you are DROPing the table. It may drop your entire data.
Update all ids that are above the one been deleted by decrementing by 1 (-1) (if there are 3 id's in auto_increment column and you delete id 2, id 3 will be set to be id = 2) and then "alter table set auto_increment = 1 to update auto_increment counter.
code(including deletion of image file from website folder:
$allGood = false;
if(isset($_GET['id']) != ""){
$item = $_GET['id'];
$query = "SELECT * FROM products WHERE id = ?";
if($getImgPath = $sqlConnection->prepare($query)){
$getImgPath->bind_param("i",$item);
$getImgPath->execute();
$result = $getImgPath->get_result();
$row = $result->fetch_array();
$deletedItemId = $row['id'];
if(isset($row['image']) != ""){
$imgPath = "../../../../".$row['image'];
if(unlink($imgPath)){
$query = "DELETE FROM products WHERE id = ?";
if($delete = $sqlConnection->prepare($query)){
$delete->bind_param("i",$item);
if($delete->execute()){
$query = "SELECT * FROM products";
if($getIds = $sqlConnection->query($query)){
while($row = $getIds->fetch_array()){
if($row['id']>$deletedItemId){
$newId = $row['id']-1;
$query = "UPDATE products SET id=? WHERE id=?";
if($updateIds = $sqlConnection->prepare($query)){
$updateIds->bind_param("ii",$newId,$row['id']);
if($updateIds->execute()){
$allGood = true;
}
}
} else {$allGood = true;}
}
}
}
}
}
}
}
}
if($allGood == true){
$query = "ALTER TABLE products AUTO_INCREMENT = 1";
if($sqlConnection->query($query)){
echo "success!";
}else{echo "error.";}
}

Return from SELECT and DELETE row in the same query

I have the following below run when creating a new member on my system. It gets them an external address to use from a list and then deletes the address used.
My concern is that two people or more may end up with the same address before it gets deleted.
Can I run this query to return an address to $addy and delete it from the table?
$query = "SELECT address FROM ext_address ORDER BY newid ASC LIMIT 1";
$res = mysql_query($query);
$row = mysql_fetch_assoc($res);
$addy = $row['address'];
mysql_query("DELETE FROM ext_address WHERE address='" . $addy . "'");

MySQL - updating the average from one table into another table

I'm a MYSQL/PHP newbie and I'm sure this is a simple question. I'm trying to calculate the average of several questions and respondents from one table and updating a Group table with that value.
For example Table answers consists of (name, group_id, TaskClarity1, TaskClarity2, TaskClarity3) in Table B i want (group_id, avg(TaskClarity1,TaskClarity2,TaskClarity3)).
This is what I've got...
$avg_task_clarity_1 = mysql_query("SELECT AVG(TaskClarity1) WHERE gruppid = '$group_id'");
$avg_task_clarity_2 = mysql_query("SELECT AVG(TaskClarity2) WHERE gruppid = '$group_id'");
$avg_task_clarity_3 = mysql_query("SELECT AVG(TaskClarity3) WHERE gruppid = '$group_id'");
$avg_task_clarity = ($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
$print_task_clarity_1" UPDATE results SET results.TaskClarity = '$avg_task_clarity'";
if (mysql_query($print_task_clarity_1)) { echo $print_task_clarity_1; } else { echo "Error TaskClarity1: " . mysql_error();
First, mysql_query() returns a resource, and you then need to extract information from it. Your query doesn't mantion any table name (I'll call it MyTable).
Also, you can get all three averages with one query.
Here's how I would start:
$table = "MyTable";
$sql = "SELECT AVG(TaskClarity1) AS avgClarity1,
AVG(TaskClarity2) AS avgClarity2,
AVG(TaskClarity3) AS avgClarity1
FROM $table WHERE gruppid = '$group_id'";
$resource = mysql_query($sql); //execute the query
if (! $resource = mysql_query($sql) ){
echo "Error reading from table $table";
die;
}
if (! mysql_num_rows($resource ) ){
echo "No records found in $table";
}
else {
$row = mysql_fetch_assoc($resource); // fetch the first row
$avg_task_clarity_1 = $row['avgClarity1'];
$avg_task_clarity_2 = $row['avgClarity2'];
$avg_task_clarity_3 = $row['avgClarity3'];
$avg_task_clarity =
($avg_task_clarity_1+$avg_task_clarity_2+$avg_task_clarity_3)/3;
//...
// other stuff you want to do
}
Please comment if this is not helpful enough, and I will revise my answer.

Check whether value exist in database

What's the best way to check whether the value is in the database?
Am I doing it correct?
$result = mysql_query("SELECT COUNT(*) FROM table WHERE name = 'John'");
$count = count($result);
you could use straight forward ,
mysql_num_rows() ;
eg :
$con = mysql_connect($host,$uname,$passwd)
mysql_select_db($dbase,$con);
$result = mysql_query($query,$con);// query : SELECT * FROM table WHERE name='jhon';
if( ! mysql_num_rows($result)) {
echo " Sorry no such value ";
}
Yes you are doing it right, if you are only concerned with checking if there are any records where name='john'
SELECT COUNT(*) FROM table WHERE name = 'John'
will return the no. of records where name field is 'John'. if there are no records then it will return 0, and if there are any records it will return the number of records.
But the above query will miss the entries where name is 'John Abraham' or 'V john', to include even these
you can modify your query like this.
SELECT COUNT(*) FROM table WHERE name like '%John%'
I'd say yes.
$result = mysql_query("SELECT COUNT(*) AS 'nb' FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['nb'];
Will give you the number of matching rows.
$result = mysql_query("SELECT COUNT(*) as user FROM table WHERE name = 'John'");
$line = mysql_fetch_array($result, MYSQL_ASSOC);
$count = $line['user'];
if($count!=0)
{
echo "user exists";
}
else
{
echo "There is no such user";
}