I want to insert into a table where the table name is a variable. I can insert to the table just fine but when I try and make it a variable I get problems. I probably just don't know the syntax very well.
Below is without the variable
$query = $pdo->prepare('INSERT INTO test (item) VALUES (?)');
Below is what I need
$type = 'test';
$query = $pdo->prepare('INSERT INTO' + $type + '(item) VALUES (?)');
I also tried doing an escape_string
$type = 'send';
$type = mysql_real_escape_string($type);
I'm pretty sure my syntax is just off.
Try this:
$type = 'test';
$query = $pdo->prepare("INSERT INTO `{$type}` (item) VALUES (?)");
Also note that PHP uses dot . not plus + as string concatenation operator. But using double quoted string for the query you can use the table variable within the string and the variable gets interpolated.
You're missing spaces on either side.
'INSERT INTO ' . $type . ' (item) VALUES (?)'
would work because the $type would be separated by spaces on either side.
Note the space after INTO and the space before (item).
Related
I don't know why this piece of code did not work, when I pass value through input text?if i am violating the rules then what is it,s correct format.
<?php
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
echo $id1; //working
echo $name; //working
echo $update; //working
mysqli_query($conn , 'update insert1 set '.$name.' = '.$update.'
where id-1 = '.$id1.'' ); //not working
// but if I manually use this as follows it works correctly
mysqli_query($conn , 'update insert1 set name = "new" where id-1 = '1'' );
?>
I'd wrap $update with single quotes (notice that I flipped the quotations) and changed id1 into $id1:
mysqli_query($conn , "update insert1 set ".$name." = '".$update."'
where id-1 = ".$id1 );
If id-1 is a string column type in the database then I'd wrap $id1 with single quotes. like this:
mysqli_query($conn , "update insert1 set ".$name." = '".$update."'
where id-1 = '".$id1."'" );
Notes:
I'd double check if id-1 is intended in the WHERE condition, because it checks if the value in that column is 2 rather than 1. WHERE id - 1 = 1 is equivalent to WHERE id = 2 but more confusing to the reader (thanks to FirstOne for pointing that out).
As mentioned in another answer, your code is vulnerable for SQL injection, I'd check this: https://stackoverflow.com/a/16282269/4283725
First of all, please indent your code properly.
Then learn (or at least try to understand) how strings concatenation works. In PHP you can use single or double quotes for strings.
What I repeat everytime to my colleague is to try (if possible) to wrap a string into the right type of quote regarding what the string can (possibly) contain.
If you have a chance to have a single quote in your string (or in one of the variables concatenated into), wrap it into doubles.
If you have a chance to have a double quote in your string (or in one of the variables concatenated into), wrap it into singles.
This can seems obvious but if you keep that in mind every time you manipulate strings, you'll be on the way for well concatenating you strings AND variables.
Also way you are passing a full raw query as a parameter is not very readable.
Put in in a separate variable and try like that :
<?php
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
$query = '
UPDATE insert1
SET ' . $name . ' = "' . $update . '"
WHERE id-1 = ' . $id1 . '
';
mysqli_query($conn, $query);
?>
You will notice that $name is not surrounded with quotes as it's a field name and not a value.
Again $id1 is not surrounded with quotes as it's an integer value and not a string value.
But if for some reason the id-1 field or your insert1 table stores numbers AS strings so you'll want to surround it with double quotes.
It appears you are not declaring a variable in your SQL statement.
Adding the dollar sign($) to declare that.
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
echo $id1; //working
echo $name; //working
echo $update; //working
mysqli_query($conn , 'update insert1 set '.$name.' = '.$update.'
where id-1 = '.$id1.'' ); //not working
//but if i manually use this as folwing it works correctly mysqli_query($conn , 'update insert1 set name = "new" where id-1 =
'1'' );
?>
Also, your code is open for SQL injection.
Hi I am using php to insert some data into a MS Access Database, which works fine in most cases, the only time it doesnt work, as far as I can see is where there is an ' in the field, in this case its an address i.e. St John's Road.
This is the query statement I am using:
$sql = "insert into tempaddress (`id`, `StreetAddress`, `Place`, `PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."','$SearchTerm')"; CustomQuery($sql);
And this is the error I am getting http://prntscr.com/58jncv
I'm fairly sure it can only be the ' within the string text that is messing it up, how can i change?
Apostrophes breaks SQL strings. So you should add slashes before each apostrophe in your SQL strings manually or use PHP's built in function addslashes().
Example:
$sql = "INSERT INTO myTable (value) VALUES ('Text that shouldn't break')";
$sql = addslashes($sql); // outputs "INSERT INTO myTable (value) VALUES ('Text that shouldn\\'t break')"
Source : php.net/manual/en/function.addslashes.php
Thanks, in the end I went with str_replace("'", "", $string);
You are using ' ' quote with the php variable $SearchTerm and use a backslash before column name.
Change your query statement to this:
$sql = "insert into tempaddress (\`id\`, \`StreetAddress\`, \`Place\`, \`PostCode`) values ('".$item["Id"]."', '".$item["StreetAddress"]."', '".$item["Place"]."',$SearchTerm)"; CustomQuery($sql);
I'm trying to copy a row from a structure I technically know nothing about.
This is what I have so far. This code does work but I'm pretty sure this isn't the most appropriate. Anyone have a better way or a right way of doing this? Any suggestions would be appreciated.
/*
$table is the table name
$id_field is the primary key
$id_value is the row I want to copy
*/
$selectEntity = $dbh->prepare("SELECT * FROM {$table} WHERE {$id_field} = :id_value");
$selectEntity->execute(array(':id_value' => $id_value));
$entity = $selectEntity->fetch(PDO::FETCH_ASSOC);
foreach ($entity as &$value){ if(is_null($value) == true) { $value = "NULL"; } else { $value = "'".htmlspecialchars($value, ENT_QUOTES)."'"; } }
//remove the primary key
$entity[$id_field] = "'"; // the ' was the only way I could get NULL to get in there
$insertCloned = $dbh->prepare("INSERT INTO {$table} (".implode(", ",array_keys($entity)).") VALUES ('".implode(", ",array_values($entity)).")");
$insertCloned->execute();
$lastInsertedID = $dbh->lastInsertId();
It's very messy.
Your quoting is not correct -- you have quotes around the entire VALUES list, they should be around each individual value. Also, you should use $dbh->escape($value) to escape the values; htmlspecialchars is for encoding HTML when you want to display it literally on a web page.
But it's better to use query parameters rather than substituting into the SQL. So try this:
$entity[$id_field] = null;
$params = implode(', ', array_fill(0, count($entity), '?'));
$insertCloned = $dbh->prepare("INSERT INTO {$table} VALUES ($params)");
$insertCloned->execute(array_values($entity));
You don't need to list the column names in the INSERT statement when the values are in the same order as the table schema. And since you used SELECT * to get the values in the first place, they will be.
I have a form that returns all of the below data
$name = $_POST['name'];
$description = $_POST['description'];
$type = $_POST['type'];
$env1 = $_POST['environment[com1]'];
$env2 = $_POST['environment[com2]'];
$env3 = $_POST['environment[com3]'];
$hltCode = $_POST['hlType[code]'];
$hltDB = $_POST['hlType[db]'];
$hltWCF = $_POST['hlType[wcf]'];
$tfsID = $_POST['tfsID'];
$release = $_POST['release'];
$createdBy = 'mhopkins';
$updatedBy = 'mhopkins';
This of course leads to a VERY long query like the following
$insertQuery = "INSERT INTO patches (name, description, type, com1, com2, bofa, code, db, wcf, tfsID, release, createdBy, updatedBy) VALUES ('".$name."','".$description."''".$type."','".$envCom1."','".$envCom2."','".$envBofA."','".$hltCode."','".$hltDB."','".$hltWCF."','".$tfsID."','".$release."','".$createdBy."','".$updatedBy."'")
$insertResult = $link->query($insertQuery);
The values section has a LOT of punctuation and many possibilities for typos. If I have my variable names be the same as the field columns, is there an easier/shorter way to do this?
Your code has sql injection vulnerabilities, I wouldn't run that code even from a trusted source.
You can try using an ORM like Idiorm, it will manage the column names and escape variables for you https://idiorm.readthedocs.org/en/latest/models.html?highlight=insert https://github.com/j4mie/idiorm/
require_once 'idiorm.php';
ORM::configure(array(
'connection_string' => 'mysql:host=localhost;dbname=my_database',
'username' => 'database_user',
'password' => 'top_secret'
));
$patch = ORM::for_table('patches')->create($_POST);
$patch->createdBy = 'mhopkins';
$patch->updatedBy = 'mhopkins';
$patch->save();
You could try to use variables to get the data out of $_POST and reuse them in the SQL string.
Like:
<?php
$descriptionFieldName = "description";
$description = $_POST[$descriptionFieldName];
$sql = "INSERT INTO patches ($descriptionFieldName) VALUES ($description);
?>
Not much shorter, well, even longer. Though this way you are only typing the form input name and the SQL column name once.
You can also try mapping an array to do the job for you, something like:
$dbColumnsToValues = array(
'column_1' => $_POST['column1'],
'column_2' => $_POST['column2'],
);
$columns = "'" . implode("',", array_keys($dbColumnsToValues)) . "'";
$values = "'" . implode("',", array_map(array($link, 'escape'), array_values($dbColumnsToValues))) . "'";
$sql = "INSERT INTO `some_table` (".$columns.") VALUES(".$values.")";
Not tested though, but you should get the point.
Also, assuming your $link object has an escape method that will make sure your input won't trigger an sql injection.
Lets assume that you have a table consisting of 3 columns: col0, col1, col2.
If you are inserting all the fields that are present in the table and in the same order, you can omit listing the column names in the query. Like instead of
INSERT INTO `table` (`col0`, `col1`, `col2`) VALUES ("{$val0}", "{$val1}", "{$val2}",);
try
INSERT INTO `table` VALUES ("{$val0}", "{$val1}", "{$val2}");
PS: PLease sanitize the variable values before using them in the query.
I try to understand manually escaping in PHP. I read this example:
if ($_POST)
{
$query = 'UPDATE
hersteller
SET
zulieferer = \''.mysql_real_escape_string($_POST['zulieferer']).'\',
telefon = \''.mysql_real_escape_string($_POST['telefon']).'\',
city = \''.mysql_real_escape_string($_POST['telefax']).'\'
WHERE
id = '.$_POST['id'];
$update = mysql_query ($query) or die (mysql_error());
}
The statement starts by an apostrophe. Unfortunately I couldn't find a discription.
1st part?
'UPDATE hersteller SET zulieferer = \'
2nd part?
'.mysql_real_escape_string($_POST['zulieferer']).'
3rd part?
', telefon = \'
4th part?
'.mysql_real_escape_string($_POST['telefon']).'
The first part is this:
'UPDATE
hersteller
SET
zulieferer = \''
note the extra '.
The escape character \ is used to escape the first ' so that it's inserted as a character into the string rather than interpreted as the end of the string.
It's similar to this:
$message = 'Let\'s get started';
$query = 'INSERT INTO table SET value = \'' . $value . '\'';
A \ character marks the following character as "plain-text", or text that has no meaning. This way, your output would look like zuliefer = 'thevalue'.
For this example, if you don't like having to escape all the characters, you can start the variable with a double quote.
$query = "UPDATE
hersteller
SET
zulieferer = '" . mysql_real_escape_string($_POST['zulieferer'])."',
telefon = '".mysql_real_escape_string($_POST['telefon'])."',
city = '".mysql_real_escape_string($_POST['telefax'])."'
WHERE
id = '".$_POST['id'] . "'";
$update = mysql_query ($query) or die (mysql_error());
-More reading on single quotes and double quotes in PHP strings
-More reading on escaping
-PHP manual on strings and meanings of symbols inside them
The statement starts by an apostrophe. Unfortunately I couldn't find a discription.
In PHP you can define strings with a pair of ' or a pair of ".
The main difference lays in the fact that "-strings are also evaluated to seek for $ variables.
For both string types you can obviously escape the ' or " character in order to make it appear in the string:
echo "He said \"Welcome\".";
// He said "Welcome".
In your case, for example, assuming the POST variable to be equal to x:
'zulieferer = \''.mysql_real_escape_string($_POST['zulieferer']).'\''
// zulieferer = 'x'
Since that string doesn't use " I'd suggest you to refactor it to be:
$a = mysql_real_escape_string($_POST['zulieferer']);
$b = mysql_real_escape_string($_POST['telefon']);
$c = mysql_real_escape_string($_POST['telefax']);
$d = (int) $_POST['id'];
$query = "UPDATE hersteller
SET zulieferer = '$a', telefon = '$b', city = '$c'
WHERE id = $d";
On a side note: you shouldn't use mysql_* functions. Use prepared statements instead.
The code is a little hard to read for two reasons:
it uses single quotes within the SQL statement and for the php string
it is one long string spanning multiple lines
This might be easier to read:
$query = 'UPDATE '.
' hersteller '.
'SET '.
' zulieferer = "'.mysql_real_escape_string($_POST['zulieferer']).'", '.
' telefon = "'.mysql_real_escape_string($_POST['telefon']).'", '.
' city = "'.mysql_real_escape_string($_POST['telefax']).'" '.
' WHERE '.
' id = '.$_POST['id'];
Edit: Regarding your comment:
$query = "DELETE FROM description WHERE id = '" . $this->getId() . "'";
This serves the same purpose as my rewrite above, only exchanging the use of single and double quotes. It uses double quotes as php string delimiters and single quotes in SQL. Both variants are fine, since both PHP and MySQL allow both kinds of quotes. Your $query variable will actually contain DELETE FROM description WHERE id = '1234'. Please note, however, both versions are not syntactically identical. PHP handles double quotes a bit differently from single quotes. In double quotes, PHP will replace variable names with the contents of that variable, in single quotes it won't.
$query = "DELETE FROM description WHERE id='$id'"; <-- PHP will insert the variable $id
$query = 'DELETE FROM description WHERE id="$id"'; <-- PHP will not touch the string