Sql Query not working! - php

INSERT INTO `test` (`x`, `y`) WHERE `id` = `$id`
VALUES (`$x`, `$y`)
Whats wrong with this query? I run this in a mysql_query() function in a php file.

You can't use a Where clause with an insert. You are either inserting a row or you're not.

If you're trying to update information from the database, use UPDATE instead of INSERT INTO in the query you're running.

You can't use a where clause on an insert. I think you might be wanting an update statement:
update test set
x = $x,
y = $y
where id = $id
When you're inserting a new value in the database, you usually don't have an ID value until after the insert (assuming you're using auto-generated IDs).

You need to remove the "WHERE id=$id" - it has no meaning in an INSERT statement.

So, either
UPDATE test SET x='x', y='$y' WHERE id ='$id';
OR
INSERT INTO test ('x', 'y') VALUES ('$x', '$y');
as stated in other posts - you cannot do an INSERT with a WHERE.

Also note that you must use single quotes (') rather than backticks (`) for values. Backticks are used when referencing column names / field names.
This:
`field` = '$value'
rather than this:
`field` = `$value`
unless you really do want to reference another field. This is sometimes what you want when copying values or matching JOINs and such. But because you have a variable there, I'm assuming you want to use single quotes rather than backticks.

Related

Replace two rows in Mysql

How I can replace everything from the base_amount and amount with the content of the base_real_amount in phpmyadmin.
Thanks
I'm not sure how to do this in phpmyadmin so I apolgoize if this doesn't answer your question. To do this with just SQL:
UPDATE `table_name` SET base_amount=base_real_amount, amount=base_real_amount;
Those aren't rows - they are columns. You could use a simple update statement to assign the value from one to the other:
UPDATE mytable
SET base_real_amount = base_amount

WHERE NOT EXISTS syntax error

I have this code that does not work, and im not sure why...
if(isset($_GET['id'], $_SESSION['username'])){
$id = $_GET['id'];
$user = $_SESSION['username'];
$query = $handler->query("INSERT INTO photolikes('User', 'Photo')
SELECT '$user', '$id'
WHERE NOT EXISTS (SELECT Id FROM photolikes WHERE User='$user' AND Photo=$id)");
}else{
}
Is just supposed to insert user and photo into a table if there is no such in there before... thanks for any help!
The SELECT is missing the FROM clause which is required when a WHERE clause is used.
That's the problem.
There's a couple of ways to fix it.
For a quick fix, you can add FROM DUAL before the WHERE.
If you don't like your MySQL queries looking like they are Oracle queries, you can use an inline view as a rowsource.
In place of FROM DUAL you could use FROM (SELECT 1) i.
That's the less-Oracle-more-MySQL-like way of fixing it. That's how I would do it.
You could also reference any table or view that you are guaranteed returns exactly one row. (It can't be zero rows, and it can't be two rows.
A couple other notes:
In MySQL, identifiers (for example column names) can be escaped with backtick characters, but not single quotes. Identifiers only need to be escaped if they contain characters that aren't allowed (in unescaped identifiers) or if the identifier conflicts with a reserved word.
INSERT INTO photolikes(`User`, `Photo`)
^ ^ ^ ^
Also, the code appears to be vulnerable to SQL Injection. Potentially unsafe values that are incorporated into the text of a SQL statement should be properly escaped. But an even better pattern is to use prepared statements with bind placeholders.
INSERT INTO photolikes(`User`, `Photo`)
SELECT '$user', '$id'
FROM <someTable>
^^^^ you miss the FROM
WHERE NOT EXISTS (SELECT Id
FROM photolikes -- Here you didnt forget.
WHERE User='$user' AND Photo=$id)")

update with max value of the column is not working in mysql

I have tried to set the max value for the particular column but that is not working for me. I do not know where i'm going wrong.
UPDATE `upload_video`
SET order_id ='select max(order_id)+1
FROM upload_video'
WHERE `video_id` = 22
This is my query i run the select max(order_id)+1 from upload_video query separately which is giving the result. But if i use this query in update query, the query is executing without error. But the order_id is not updating properly. please help me
Your query is almost correct in standard SQL, you only need to use brackets () instead of apostrophe ':
SET order_id = (SELECT MAX(...) ...)
but MySQL doesn't allow you to update a table while selecting from the same table, a workaround is to use a subquery that calculates the value that you need, and to join your subquery with the table you need to update:
UPDATE
upload_video JOIN (SELECT COALESCE(MAX(order_id),0)+1 max_id
FROM upload_video) s
SET
upload_video.order_id=s.max_id
WHERE
video_id=22
Please see fiddle here.
You have a typo in the statement, you used UPADTE instead of UPDATE.
One problem is, don't quote the subquery. You have used single quotes, which means the expression select max(order_id)+1... was interpreted as a text literal (a varchar). But you clearly don't want that (I guess order_id is a number). What you want instead is to evaluate the subquery. However, if you try:
UPDATE `upload_video`
SET order_id =(select max(order_id)+1
FROM upload_video)
WHERE `video_id` = 22
then MySQL doesn't allow it (I didn't know about that). Other databases such as PostgreSQL allow it. So you might need two statements:
select #id = coalesce(max(order_id), 0) + 1 FROM upload_video;
UPDATE `upload_video` SET order_id = #id WHERE `video_id` = 22;
Please note this works in MySQL but not in other databases.
Try this:
UPDATE `upload_video`
SET order_id =(select COALESCE(max(U2.order_id),0)+1
FROM upload_video U2)
WHERE `video_id` = 22
Peraphs this query goes in error because MySql doesn't want to use the same table in UPDATE and in subquery.
If your case please write two queries.
The first get the maximum value, the second does update

How do I insert a value to a specefic row?

I know how to do an insert
database::query("INSERT INTO cr VALUES ('$flname', '$email', '$pass', '$ext')");
and how to find a row
database::query("SELECT * FROM cr WHERE email='$email'")
but how do I do both, i.e. select a specefic row and then insert/update that value.
database::query("update cr set FileName='$flname', Email='$email', Pass='$pass', Ext='$ext' where email='$email');
What you want is to UPDATE an existing row. To avoid injection, you escape variables with mysql_real_escape_string and/or by preparing and binding parameters.
Inserting data into a specific row requires that this row exists; in that case you perform an UPDATE which usually has a WHERE condition just like a SELECT has.
To avoid SQL injection you want to use mysql_real_escape_string() on your variables; for numeric data it is also a good idea to cast to the desired type. Another option would be using prepared statements.
if you only want to change field in existing row:
UPDATE cr SET col = 'val' WHERE id = x
or if you wan't to insert or update:
REPLACE cr VALUES ($id, '$flname', '$email', '$pass', '$ext')
in the latter you have to put unique key on id (or other column)
there is also
INSERT INTO cr (...) ON DUPLICATE KEY UPDATE col = 'val'

Can you DROP TABLE IF EXISTS by specifying database name with table?

I am trying to drop a table in a database with the following query statement:
mysql_query('DROP TABLE IF EXISTS "dbName.tableName"') or die(mysql_error());
But I keep getting an error. Does anyone know if specifying the dbName.tableName is invalid?
mysql_query('DROP TABLE IF EXISTS `dbName`.`tableName`') or die(mysql_error());
You should use backticks instead of double quotes like this:
mysql_query('DROP TABLE IF EXISTS `dbName`.`tableName`');
You can't use double quotes to quote db/table names, instead you either leave them unquoted or use backticks. But to answer your question, yes it is perfectly valid to specify the database name.
DROP TABLE `dbName`.`tableName`

Categories