How to use a value from SELECT in UPDATE statement? - php

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());

Related

Replace variable with query

I am pretty new to using mysql and variables in php.
I have this code
mysql_query("INSERT INTO `forum_threads` (`name`, `byid`, `cid`,
`content`, `time`, `lastreplied_time`, `lastreplier_id`) VALUES
('{$title}', '{$uid}', '{$cid}', '{$content}', '" . time() . "', '" .
time() . "', '{$uid}');") or die(mysql_error());
In my php file, I want byid to be the value of id in my table forum_users. So can I replace {$uid} with something that will get the value from forum_users. Because I don't think {$uid} is working correct.
I found this code
/* Non-existant forum account */ final public function
createForumAccount($uid) {
$getHabboUser = mysql_query("SELECT * FROM
`users` WHERE `id` = '{$uid}' LIMIT 1");
I assume that the function of that code is to get the {$uid} equal the id from the users table, I want to make the {$uid} to equal the id from the forum_users table.
Then I found this code:
final public function getUserData($uid, $var) {
if($this->checkForAccount($uid) == true) {
$check = mysql_query("SELECT `{$var}` FROM `forum_users` WHERE `uid` = '{$uid}' LIMIT 1") or die(mysql_error());
return mysql_result($check, 0);
}
}
That code wants the {$uid} to equal forum_users id. And that is exactly what I want, but it doesn't equal that, it equals the id from the users table instead, I assume it might collide with eachother or something.
How can I solve this? Can I replace {$uid} in my first code, so byid is selected instantly from forum_users? Can I make a new variable that equals forum_users.id?
First of all this sql query makes no sense. However I am also not sure your question either. If your wanting to change byid to id in your table then you must alter the table. But here is a cleaner version of your sql query.
try:
mysql_query("INSERT INTO forum_threads SET name=\"".$title."\",byid=\"".$uid."\",cid=\"".$cid."\",content=\"".$content."\",time=\"".time()."\",lastreplied_time=\"".time()."\",lastreplier_id=\"".$uid."\" WHERE id=\"".$uid."\" LIMIT 1") or die("Error: ".mysql_error());
//You Change ID to byid
to change byid to ID
mysql_query("ALTER TABLE `forum_threads` CHANGE `byid` `id` int NOT NULL")or die("Error: ".mysql_error());
// this will change the column byid to id
Just Remember Mysql_connect() and mysql API are old and not used after php 7 so start to learn mysqli api
http://php.net/manual/en/book.mysqli.php

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));

SQL insert and update in the same time

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.

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.

DELETE from mysql table WHERE column equals value AND column2 equals value2

Having some trouble getting this query to work correctly.
mysql_query("DELETE FROM `table` WHERE `id` = '$id' AND 'username' = '$username' ");
tried replacing variables with actual data and running it in phpmyadmin to no success
any thoughts?
You're quoting the username column with ' instead of `
use:
mysql_query("DELETE FROM `table` WHERE `id` = '$id' AND `username` = '$username'");
not:
mysql_query("DELETE FROM `table` WHERE `id` = '$id' AND 'username' = '$username'");
Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Categories