SQL insert and update in the same time - php

Hey I have a query that will insert into the table a new data and I want that in the same time update an outher table with the id of the new data that I have entered. ex:
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$query = mysql_query("SELECT `id` FROM `test` WHERE `name` = 'Mark'");
$id = mysql_result($query,0);
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
How do I do it at same time? because doing it this way I only insert the new data and I dont update the other.
Cumps.

Try this :
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
I've changed the backticks to single quotes in your first insert for the values, backticks should never be used for field values.
Also I've changed it to use only two queries, the mysql_insert_id() will get the last inserted id without you needing to query it.
Ref : http://www.php.net/manual/en/function.mysql-insert-id.php

First of all, you do not need the select to get the id, there is mysql_insert_id() for that.
Then you have to use a transaction to make both queries feel like executed at the same time:
mysql_query('BEGIN');
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_query("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
mysql_query('COMMIT');
A transaction makes sure both statements are executed, and no other script can come between them in any way.

Related

Saving a string to a database

I am trying to save a string which is just $id = "27491"; into a database table called users under a field called user id here's what I have tried currently but it's not working...
mysqli_query($DB,"INSERT INTO `users` SET `id` = '".$id."'");
EDIT: The content just does not go into the database, the issue before was just a typo.
Also does not work with my $title string.
mysqli_query($DB,"INSERT INTO `users` SET `title` = '".mysqli_real_escape_string($DB,$title)."'");
You can use like below, One more suggetion for you, this is not good practice to use space in field name. So, you can use field name like user_id, this is good to go.:
mysqli_query($DB,"INSERT INTO `users` SET `user id` = '".$id."'");
// ^ you miss
OR
mysqli_query($DB,"INSERT INTO `users` (`user id`) VALUES('".$id."')";
Parenthesis aren't closing in your code...
mysqli_query($DB,"INSERT INTO `users` SET `user id` = '".$id."'");
Please try this. I hope this will help you.
Change your query to -
mysqli_query($DB,"INSERT INTO `users` SET `title` = ".mysqli_real_escape_string($DB,$title));

How to use a value from SELECT in UPDATE statement?

below is what I am trying to accomplish. I am trying to retrieve an integer value using a SELECT statement which I will inturn pass into the UPDATE statement, but I have not been sucessful with it. Below is what I have done so far and it doesn't work. Please any suggestion will be highly appreciated. the $empID is passed from a form using php.
$getemID ="SELECT `addressID` FROM `address` WHERE `userID` =$empID";
$myemID = mysql_query($getemID) or die(mysql_error());
$addrID = $myemID["addressID"];
$sql4="UPDATE `address`
SET `line1`='$line1', `line2`='$line2', `city`='$city', `zip`='$zip'
WHERE `addressID`=$addrID";
$res = mysql_query($sql4) or die(mysql_error());
While you should not use the deprecated mysql_* functions, the following still stands:
The return value of the mysql_query call is not an array, but a resource. Use this resource in a call like mysql_fetch_array to get the data. Then you can use that data for the other query.
Why not do it in a single query like below
UPDATE `address`
SET `line1`='$line1', `line2`='$line2', `city`='$city', `zip`='$zip'
WHERE `addressID` IN (
SELECT `addressID` FROM `address` WHERE `userID` =$empID
)
After select query you have to fetch them using mysql_fetch_array. As given below:
$getemID ="SELECT `addressID` FROM `address` WHERE `userID` =$empID";
$myemID = mysql_query($getemID) or die(mysql_error());
$row = mysql_fetch_array($myemID);
$addrID = $row["addressID"];
$sql4="UPDATE `address`
SET `line1`='$line1', `line2`='$line2', `city`='$city', `zip`='$zip'
WHERE `addressID`='$addrID' ";
$res = mysql_query($sql4) or die(mysql_error());

The best Mysql query

I'm sending form data to db with UPDATE query:
mysql_query("UPDATE users SET price = '100-200' WHERE login = '$login'");
mysql_query("UPDATE users SET city = '$city' WHERE login = '$login'");
My question is: how to rebuild it to have query which writes data in db, but do not remove older posts.
For example: If user enters data 'price' and 'city', and after this, he wants to change only 'city', script with update will cancel 'price' and leave blank field in db.
How to make it to update (like in example) only city, but to leave price as it was before (100-200). Is there a proper query for this?
You will want to do a check for NULL or empty variables before running the SQL Statements. Something like this:
if(!empty($price))
{
mysql_query("UPDATE `users` SET `price` = '".$price."' WHERE `login` = '".$login."';");
}
if(!empty($city))
{
mysql_query("UPDATE `users` SET `city` = '".$city."' WHERE `login` = '".$login."';");
}
use "INSERT INTO table (column1, column2,column3) VALUES (val1,val2,val3)";
ps: mysql_* is deprecated update to PDO or MySQLi

Update statement not updating table but inserting new entry into table instead

For the life of me I cannot figure out why my update statement will not update the table row but instead it creates a new row. I have an ID column that is the unique identifier and is auto_increment, I am just not sure if you can update an auto_incremented data set the way i am trying to.
I have a form that is echo'ing data from the database into the fields and then am using it to edit the fields and update them.
The code:
<?php
$EntryID = $_GET['Eid'];
$IDlist = mysql_query("SELECT * FROM BD WHERE Id='$EntryID'");
$IDresults = mysql_fetch_array($IDlist);
$update_query = "UPDATE `BD` SET `Id` ='$IDresults['Id']',`EntryTitle` = '$MyTitle',`EntryDescription` = '$MyDescription',`Category` = '$MyCategory' WHERE `Id` ='$EntryID'";
mysql_query($update_query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
header('location: /admin/bd-edit-entry.php?sub=1');
exit();
}
mysql_close($con);
?>
Any help or advice would be a great.
SET `Id` ='$IDresults['Id']'
should be either:
SET `Id` ='$IDresults[Id]'
or
SET `Id` ='{$IDresults['Id']}'
If you turn on error reporting, you should get errors about a bad index.
Or you can leave this column out of the update entirely, since this column isn't changing.

Adding rows to mysql - get sorted randomly - want them on top

I have kind of a "problem" that I do not know how it happened. If I add rows to my table via php it just adds them randomly somewhere. But I want them to be added on top. Instead it justs add them all over the table.
$name = ($_GET["name"]);
$sql = "INSERT INTO $DB_Table VALUES('$name')";
$number = ($_GET["number"]);
$sql = "INSERT INTO $DB_Table VALUES('$number')";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
mysql_query("INSERT INTO $DB_Table (Name,number)
VALUES ('$name','$m_yolo')");
$res = mysql_query($sql,$con) or die(mysql_error());
mysql_close($con);
if ($res) {
echo "success";
}else{
echo "faild";
}// end else
?>
There is no such thing as row ordering in a relational table. If you want them ordered, you need to use an ORDER BY clause. You can add a TIMESTAMP column, which you can sort on when you select your data: 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
Create another table but add an ID auto-increment column in it:
CREATE TABLE IF NOT EXISTS `table` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`number` int(10) NOT NULL,
PRIMARY KEY (`id`)
);
Then you can insert new rows like this:
$sql = "INSERT INTO $DB_Table (id, name,number) VALUES ('', '$name', '$number')";
Your new entries will be sorted by id then. You can order them in you select query with:
$sql = "SELECT 'name', 'number' FROM `table` ORDER BY 'id' DESC";
One remark about your code though: it is not safe to directly use the values from $_GET as you do at the beginning of your code. Try using mysql_real_escape_string() for example.

Categories