MySQL - Delete a row, how? - php

Can anyone show me a query in MySQL that would delete rows from all available columns.
I use this to insert rows:
$sql = "INSERT INTO " . KEYS . " // KEYS is a constant
(key, user_id, time, approved)
VALUES ('" . $randkey . "', '" . $user_id . "', '" . $time . "', '0')";
I need the opposite of this now, delete created rows.

delete from <table> where ....
Keep in mind that the delete statement is always for an entire row.

Using similar syntax sql = "DELETE FROM " . KEYS . " WHERE 1=1";
Replace 1=1 with the conditions for the row you want to delete or it will delete all rows.
Also, it's good to get out of the habit of just dropping variables into SQL as soon as possible, because it will open your code up to SQL Injection attacks. Look into using parameterized queries.

Related

Trouble specifying my tablename inside query because of dot notation

I'm having trouble specifying my tablename inside the following query.
$sql = "INSERT INTO db269193_crud.posts (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
The tablename is: db269193_crud.posts. I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
So the table name becomes: db269193(dot)posts. This dot however keeps lighting up in my editor as an incorrect syntax.
I need someone's help to tell me if I specified the table name correctly or if I have to use a variable to hide the dot notation like:
$tablename = 'db269193.crud';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You can put the entire name in backticks to escape it:
INSERT INTO `db269193_crud.posts` (post_title, description)
VALUES ('" . $title . "', '" . $description . "')
As for the rest of your statement, I would encourage you to use parameters instead of munging the query string. By putting random strings in the query, you are just inviting syntax errors and SQL injection attacks.
I can't specify the table name as 'posts' because of my hostingprovider. They only allow me to specify it in conjunction with my databasename (which is db269193).
I pretty much doubt that as it would require DB changes which simply make no sense. I assume that it's your fault as you did not select DB to use in the first place. Check how you connect and ensure you provide DB name as well or at least you mysqli_select_db() or equivalent.
$tablename = 'db269193.crud';
You can use backticks when name of table or column conflicts or is reserved word:
$tablename = '`db269193.crud`';
or
$tablename = '`db269193`.`crud`';
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('" . $title . "','" . $description . "')";
You are complicating simple strings with unnecessary concatentation. This will work and is less error prone:
$sql = "INSERT INTO $tablename (post_title,description)
VALUES ('{$title}','{$description}')";
however you are still seem to be vulnerable to sql injection here. I'd recommend switching to PDO.

insert with multiple select statements and php variables

I want to insert record in product table from two tables i.e adminlogin and product_category and with few php variables.my query is not working giving syntax error..please help
$sSQL4 =
"INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) Select admin_id from adminlogin where username='" .$user_name. "',
SELECT category_id,'',
'" .$title. "',
'" .$price. "',
'" .$file_name1. "',
'pending' from product_category WHERE category_name='" .$category. "'";
$result4= mysql_query($sSQL4);
The reason you're getting a syntax error is because you're not using valid SQL. The INSERT INTO ... SELECT syntax only works with a SINGLE select query.
Currently, you're basically linking 2 completely random queries, and mysql hasn't the slightest clue how to link them (even if it were possible).
What you want instead, is either to do 2 queries:
1. A query to get the username
2. The query to insert... select, while adding the username as a static string yourself.
Alternatively, you can use a sub-query to add the username. However, since the subquery is repeated for every single row inserted, this is actually a lot slower(!).
With a subquery, your query would look like:
$sSQL4 = "INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) SELECT (SELECT admin_id from adminlogin WHERE username='" .$user_name. "'), category_id,'','" .$title. "','" .$price. "','" .$file_name1. "','pending' FROM product_category WHERE category_name='" .$category. "'";
$result4 = mysql_query($sSQL4);
With 2 queries, you would get something like:
$q = mysql_query("SELECT admin_id FROM adminlogin WHERE username='" . $user_name . "'");
$adminId = mysql_fetch_object($q)->admin_id;
$sSQL4 = "INSERT INTO product(user_id,category_id,product_id,title,price,product_img,product_status) SELECT '".$adminId."', category_id,'','" .$title. "','" .$price. "','" .$file_name1. "','pending' FROM product_category WHERE category_name='" .$category. "'";
You are using wrong syntax. Use 'INSERT INTO(col1,col2) Values(val1,val2)'

wrong query inserting value in specific row

I'm trying to execute the following query where I want to add a value in the column firstime in the corresponding row with $netid and mac.
$query="INSERT INTO node WHERE netid='".$netid."' AND mac='" . $_GET['mac'] . "' (firstime) VALUES ('" . $firstcheck . "')";
mysql_query($query, $conn) or die("Error executing query: ".mysql_error($conn));
when I try I get the following error message:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE netid='28' AND mac='24:A4:3C:40:4D:EB' (firstime) VALUES ('2014-01-16 12:0' at line 1
Any Idea??
You cannot use WHERE clause for INSERT query since it makes no sense
Here is a documentation page about its proper syntax: http://dev.mysql.com/doc/refman/5.6/en/insert.html
A scientific guess: what you need is UPDATE
Perhaps you want an update:
update node
set firsttime = '" . $firstcheck . "'
WHERE netid = '".$netid."' AND mac = '" . $_GET['mac'] . "';
insert inserts a new row into the table, not a new value into the row.
update updates a value in a row.
The WHERE conditions must go at after the colums and values declaration.
INSERT INTO node (firstime) VALUES ('" . $firstcheck . "') WHERE netid='".$netid."'
AND mac='" . $_GET['mac'] . "'";
Also use prepared statements and sanitize user submitted data, in order to prevent a SQL INJECTION which is a present and clear threaten.

Escaping a string being inserted into Mysql

I have tried all combinations of single quotes, double quotes etc but the following code keeps erroring with sql syntax error. The en and cy are paragraphs of text. I think I must be missing something obvious but I cant see it. Any suggestions?
$insert_dana = mysql_query("UPDATE Contributor (Summary_en,Summary_cy) VALUES ('" . mysql_real_escape_string($insert[en][0]) . "','" . mysql_real_escape_string($insert[cy][0]) . "') WHERE id='$insert[id]'");
You mixed insert and update statement syntax. Use this one
$insert_dana = mysql_query("UPDATE Contributor set Summary_en = '" . mysql_real_escape_string($insert[en][0]) . "', Summary_cy = '" . mysql_real_escape_string($insert[cy][0]) . "' WHERE id='$insert[id]'");
you're confusing the UPDATE- and the INSERT-syntax. for UPDATE, it's like:
UPDATE
table
SET
field = 'value'
WHERE
...
while an INSERT looks like:
INSERT INTO
table
(field)
VALUES
('value')
you can't write an UPDATE with (field) VALUES ('value')-syntax.

Is there a better way to insert values to MySQL query than just VALUES($var1, $var2, $var3)?

I just have the array of 15 values that all need to be inserted into the table.
And I was just wondering if there is anything like this:
INSERT INTO table VALUES($myarrayofvalues)
Just curious, would be very useful.
Update:
Just one row with 15 columns.
$query = "INSERT INTO table VALUES('" . implode("', '", $myarrayofvalues) . "')";
Edit:
If you haven't done your escaping yet, you can do that in a tiny loop before the above statement, something like:
foreach($myarrayofvalues as $k=>$v)
$myarrayofvalues[$k] = mysql_real_escape_string($v);
While you can do what's show in the answer by Rick, it is open to SQL injection.
There is really no good way to do this without some kind of column mapping. That is something to state element 1 is a string, element 2 is an integer.
As such, I see two choices:
Escape everything
$values = array();
foreach ($myarrayofvalues as $value) {
$column[] .= "'" . mysql_real_escape_string($value) . "'";
}
$sql = "INSERT INTO table VALUES(" . implode(',', $values) . ")";
Write the complete SQL statement
$sql = "INSERT INTO table (column1_string, column2_int, ...)
VALUES ('" . mysql_real_escape_string($myarray[0]) . "', " . (int)$myarray[1] . ", ...)
I prefer #2 because it is more readable and less brittle. Currently if your schema or array changes, your code breaks.

Categories