A simple question!:
Can I use my field value in an insert query?
For example, I've a field named id, it is an auto_increment field. i want to add this field value to another field. while I'm inserting it.
A simple php code of my need:
$query_1 = mysql_query("INSERT INTO table (name) VALUES ('abcd')"); // id automatically increment
$query_2 = mysql_query("SELECT id FROM table WHERE name = 'abcd'"); // selects previous id
// fetches result //
$query_3 = mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');
Can you convert it to just 1 query?
Thanks ...
I don't think you can do it in one query but you can do it in 2 for sure:
mysql_query("INSERT INTO table (name) VALUES ('abcd')");
$id = mysql_insert_id();
mysql_query("UPDATE table SET code = '" . $id + 1000 . "' WHERE id = '" . $id . "');
Here's how you do it with one query:
$query_1 = "INSERT INTO table (note) VALUES ('abcd'); UPDATE table SET code = LAST_INSERT_ID() + 1000 where id = LAST_INSERT_ID()";
I can't remember if mysql allows multiple queries in one command - I think maybe not, so try this:
$query_1 = "INSERT INTO table (note) VALUES ('abcd')";
$query_2 = "UPDATE table SET code = id + 1000 where id = LAST_INSERT_ID()";
Related
I have a table
items: id, userid, item_name, item_description
I want to update a row and used the following sql statement for it.
$updateQuery = "UPDATE items SET item_name = '$item_name',
item_desc = '$item_desc' WHERE userid = '$userid'
AND item_name = '$old_name'";
But it fails. Is it because I used the item_name field, which is to be updated, for selecting the row?
I think I see the problem
item_desc = '$item_desc'
"4 columns id, userid, item_name, item_description."
Change your query to
$updateQuery = "UPDATE items SET item_name = '$item_name', item_description = '$item_desc' WHERE userid = '$userid' AND item_name = '$old_name'";
you not update item_name because you used it in where clause
or
you can echo this string and run in database terminal to verify.
Try :
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "';"
Please notice, in your query, you are referring the last column as "item_desc" which does not exist, as the actual column name is "item_description" .
MySQL is treating "item_desc" as a separate column in your table, but unable to find it, and hence the error.
Also, it is a good idea to pay attention to how you are concatenating your variable to your query. After equal to(=) sign, always use this notation ' ".$variable_name." ' to concatenate. Example:
select column1, column2 from table1 where (column1 = ' ".$variable_name." ' && column2 = ' ".$variable_name." ') ";
You have to concatenate the strings.
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "'";
Instead of item_desc, it should be item_description.
I have a select statement and an update statement. What I would like to do in the update statement is set the value of 'recipes_saved' to the result of the select statement. I have tried to use this:
$query = "UPDATE `users` SET `recipes_saved` = ('SELECT `recipe_1_name` FROM `carbohydrates`') WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
$data= mysqli_query($dbc,$query) or die('Query failed: ' . mysqli_error());
but the query fails.
Any help would be much appreciated.
I think you have an extra ' in your 'SELECT and also in your FROM carbohydrates' and use LIMIT again like:
Try to copy the query below:
$query = "UPDATE `users` SET `recipes_saved` = (SELECT `recipe_1_name` FROM `carbohydrates` LIMIT 1) WHERE `user_id` = '" . $_SESSION['user_id'] . "'";
You could of course remove the back tick if you want to make it less cluttering, like:
$query = "UPDATE users SET recipes_saved = (SELECT recipe_1_name FROM carbohydrates LIMIT 1) WHERE user_id = '" . $_SESSION['user_id'] . "'";
As far as I know, you do not need so many quotes in your query. Try:
$query = "UPDATE users SET recipes_saved = (SELECT recipe_1_name FROM carbohydrates) WHERE user_id='" . $_SESSION['user_id'] . "'";
It would also be useful to log in to your database directly (either command line or a GUI client) and try running the query:
UPDATE users SET recipes_saved = (SELECT recipe_1_name FROM carbohydrates) WHERE user_id='username'
and see if that works.
I'm trying to do something that may be too complicated for MySQL
If a row exists i'd like it to update a counter and if not insert the row...I did a search and found this...
$query = "insert into TABLE
(`id`, `item`, `count`, `option1`, `option2`)
values
('$cartName', '$sku', 1, '$option1', '$option2')
on duplicate key
update count = count + 1";
but I don't have a key in the table so the "on duplicate key" won't work, the query needs multiple ANDs to check the row based on the id, item, and 2 option values.
an added thing is to have mySQL return a count of all count values based on the item
This is what I have currently (modified from search :), does anyone know how to reduce this into a single query?
option1 and option2 are variable and could be null so that's why the 2 if statements and is called from AJAX so the $message is used to update the javascript client side.
$query = "update TABLENAME set count=count+1 where item='$item'";
if($option1) $query .= " AND option1='$option1'";
if($option2) $query .= " AND option2='$option2'";
$result = mysql_query($query) or die("Error:".mysql_error() );
if (mysql_affected_rows()==0) {
$query = "insert into $table11 (`id`, `item`, `count`, `option1`, `option2`) values ('$id', '$item', 1, '$option1', '$option2');";
$result = mysql_query($query) or die("Error:".mysql_error() );
}
//total count for all items with specific id
$query = "SELECT SUM(count) FROM TABLENAME WHERE id='$cartName'";
$result = mysql_fetch_row(mysql_query($query)) or die("Error:".mysql_error() );
$message = $result[0];
Is this possible using only mysql:
Insert a new column and example - "pos".
Every row in the table has to have unique,incresing value of "pos" like - 1,2,3,4,5.
In php this would be an easy job:
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$counter = 0;
while($row = mysql_fetch_array($result)){
mysql_query( "UPDATE example SET pos = ".++$counter." WHERE id = ".$row['id']." );
}
As already suggested, the most efficient solution is to use auto incremental on pos.
Alternatively if your use case do not permit you, then try similar:
"UPDATE example SET pos = ((select max(pos) from example) +1) WHERE id
= ".$row['id']."
yes you can do it like that
UPDATE example SET pos = pos+1 WHERE id = ".$row['id']."
Give your pos mysql field the auto_increment attribute - this will index it, make it unique, and increment by 1 on each insert
how do i check if the value of a column is null, and only then execute the query? for example:
col1 col2 col3
01 abc
i run a query which first checks if the record exists or not; if it exists, it should execute the update query and if it doesn't exist, it executes the insert query. how do i check if col3 is null and if it is null, it should execute the update query. .
$sql = "SELECT uid FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Not really checking a value of the column, but I don't think you actually need that.
You need to have uid as a UNIQUE column. You try to insert a row for a new user with the given uid; if it finds the user with the same uid, then you do the update instead.
UPDATE:
I guess you did not bother to read the link.
I did not test it, but it should be something like this:
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session='SeSsIoN_iD'
This will insert the user if he does not exist, and if he does, it will set a new session key. OR, if you want to preserve the old session key if he already has one,
INSERT INTO users (uid, name, session)
VALUES ('login', 'Real Name', 'SeSsIoN_iD')
ON DUPLICATE KEY UPDATE session=IFNULL(session, 'SeSsIoN_iD')
One query, not three. You were not already doing it.
$sql = "SELECT * FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
$res = mysql_fetch_array($sql);
if(!empty($res['col3'])) {
insertUser($user_id,$sk, $conn);
}
}
else
{
updateSessionKey($user_id,$sk,$conn);
}
Is this what you mean?
If the record does not exist -> insert.
If the record does exist and its col3 is null -> update
If the record does exist, but its col3 is not null -> do nothing?
That could be achieved like this (untested):
$sql = "SELECT uid, col3 FROM `users` WHERE uid = '" . $user_id . "'";
$result = mysql_query($sql,$conn) or die('Error:' .mysql_error());
$totalrows = mysql_num_rows($result);
if($totalrows < 1)
{
insertUser($user_id,$sk, $conn);
}
else
{
$col3value = mysql_result($result, 0, 'col3');
if (is_null($col3value))
{
updateSessionKey($user_id,$sk,$conn);
}
}