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.
Related
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.
I am new to PHP and I am having trouble solving this: I have an array (PHP) that looks like this
"tandemArray":["English", "German"]
As seen in my LogCat (Eclipse, I return the array to the Android client and log it in Eclipse). I want to query the database with a string similar to:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ("English", "German"); // The tandemArray
I've tried different approaches but without success. For instance:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ("' . implode('","', $tandemArray) . '")';
I would greatly appreciate any help!
The code uses mismatching quotes and double-quotes in your shown approach; try reversing the ' and " to be like this:
$myQuery = "SELECT id"
. " FROM my_users"
. " WHERE 1=1" // using an actual WHERE-clause
. " AND Tandem_Tongue IN ('" . implode("','", $tandemArray) . "')";
The correct code is provided by ChrisForrence:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN ('" . implode("','", $tandemArray) . "')';
The problem was in quotes mismatch.
Not positive but I think you've mismatched the quotes and periods in your example. Should be more like:
$myQuery = "SELECT id
FROM my_users
WHERE // some code
AND Tandem_Tongue IN (".implode("','",$tandemArray).")';
I just used single quotes around the array elements since that is usually easier for me to decipher in mysql queries. Eg. 'English', 'German' You'll need to adjust if you need double quotes.
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.
I have an HTML form which submits values to the following PHP file, which inserts them into a MySQL database:
<?php
$con = mysql_connect("*","*","*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("*", $con);
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
Sometimes an input field in the HTML form will be left empty and in this case I do not want anything inserted into the database. I want the value to remain NULL. At the moment when I fill in my form like this:
Home team: Blue team
Away team: [empty]
Result: Won
The following is inserted into my database:
Home team: Blue team
Away team: ' '
Result: Won
What I want to be inserted/not inserted is:
Home team: Blue team
Away team: NULL
Result: Won
I've hunted hours for a solution. Can anyone help? Thank you.
You can use the NULLIF function from mysql database. What it does is, it takes 2 parameters and return null if they are same. So basically you can change your code to be like following:
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
(NULLIF('" . mysql_real_escape_string($_POST['hometeam']) . "', ''),
NULLIF('" . mysql_real_escape_string($_POST['awayteam']) . "', ''),
NULLIF('" . mysql_real_escape_string($_POST['result']) . "', ''))";
It will basically check if the entered value is ''(empty string), and if that's the case, it would instead save NULL in the database. You can even trim leading or trailing spaces from your variables before passing onto NULLIF, so if someone only enters spaces in your input boxes, it still saved NULL.
Also, as Michael said, it would be safer and better if you move on to PDO or mysqli extension. Hope my answer helps.
In your code, replace:
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
'" . mysql_real_escape_string($_POST['awayteam']) . "',
'" . mysql_real_escape_string($_POST['result']) . "')";
With:
if($_POST['awayteam'] == '')
$awayteam = 'NULL';
else
$awaytem = "'" . mysql_real_escape_string($_POST['awayteam']) "'";
$sql="INSERT INTO scores (hometeam, awayteam, result)
VALUES
('" . mysql_real_escape_string($_POST['hometeam']) . "',
" . $awayteam . ",
'" . mysql_real_escape_string($_POST['result']) . "')";
Don't quote them inside your query. Instead, build variables first, and append quotes to the escaped string values outside the query, giving you the ability to insert NULL keywords if your strings are empty:
// If any is not set or empty in the POST, assign the string "NULL" unquoted to a variable
// which will be passed to MySQL as the unquoted NULL keyword.
// Otherwise escape the value from $_POST and surround the escaped value in single quotes
$ateam = !empty($_POST['awayteam']) ? "'" . mysql_real_escape_string($_POST['awayteam']) . "'" : "NULL";
$hteam = !empty($_POST['hometeam']) ? "'" . mysql_real_escape_string($_POST['hometeam']) . "'" : "NULL";
$result = !empty($_POST['result']) ? "'" . mysql_real_escape_string($_POST['result']) . "'" : "NULL";
// Then pass the three variables (already quoted if necessary) directly to the query.
$sql="INSERT INTO scores (hometeam, awayteam, result) VALUES ($hteam, $ateam, $result);
In the long run, it is recommended to begin using a MySQL API which supports prepared statements, like PDO or MySQLi. They offer better security, can handle input NULLs more elegantly, and the old mysql_*() functions are soon to be deprecated.
Or if you have access to db alter the columns( that are optional) and set them as NULL by default.
i.e. if nothing is inserted in that column NULL will be displayed by default.
Why not replace ' ' and other invalid forms of data with 'null'?
OR
Check if $_POST['data'] is equal to ' ' or '' and if true, set them to 'null'.
Also,
Instead of mysql_real_escape_string, use the PHP function 'addslashes'.
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.