CodeIgniter phpMyAdmin - Inserting into table with a space in the name - php

$this->db->insert('Table One',$data);
This would error. And showing the equivalent sql, insert into.
INSERT INTO `Table` One (`col1`, `col2`) VALUES ('----', '------')
Is there any way to insert?
Maybe the use of a wildcard perhaps? or any special character to substitute space for phpmyadmin to udnerstand? or is it phpmyadmin's fault?

Unfortunately it seems that the active record library doesn't support table names with space in. I looked into the core files and the insert() function calls the protect_identifiers function on the table name and in system/database/DB_driver.php there is the following code
// If the item has an alias declaration we remove it and set it aside.
// Basically we remove everything to the right of the first space
$alias = '';
if (strpos($item, ' ') !== FALSE)
{
$alias = strstr($item, " ");
$item = substr($item, 0, - strlen($alias));
}
So everything after the first space is removed. So it looks like your only options are to do the query like
$this->db->query('INSERT INTO `Table One` ...');
Or to remove spaces in your table names
Sorry. Hope that helps

If you have a space in your table name, you need to quote the full name:
INSERT INTO `Table One` (`col1`, `col2`) VALUES ('----', '------')

I found a similar issue when doing an update call
$this->myBaseTable = "my table";
$this->db->update($this->myBaseTable); //errors
It seems to work fine if you added the ticks into the table declaration ie
$this->myBaseTable = "`my table`";

Related

Use a function which mimics the original mysql_real_escape_string

I try to extract some information from one table and insert it to another. I'm using the following function from https://php.net/mysql_real_escape_string to handle the escape characters.
<?php
function mysql_escape_mimic($inp) {
if(is_array($inp))
return array_map(__METHOD__, $inp);
if(!empty($inp) && is_string($inp)) {
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
}
return $inp;
}
?>
The string I deal with is in html form with double and single quotes like
<input type="radio" value="choice_3" checked="true"/> Eat pig's belly and swine's matrix
I have to use string concatenation to write queries because column names and table names are dynamic.
$query .= "'".mysql_escape_mimic($string)."', ";
I know there is some kind of syntax error but I don't know how to fix it. Can anyone help me with it? Thanks.
I suspect your problem is with this line:
$query .= "'".mysql_escape_mimic($string)."', ";
That concatenation will leave a trailing comma, which almost certainly is causing a syntax error in your SQL. In SQL, any set of terms that are to be separated by commas must not have a trailing comma at the end of that set.
You can use a PHP trimming function to trim off the trailing ", " after you are done building the concatenated string.
I would also like to note that you can accomplish what your stated goal is ("extract some information from one table and insert it to another") entirely within the database. That is, you don't need to SELECT it into your application and then re-INSERT into the other table, thus avoiding this problem entirely.
If the two tables have identical columns, then something like this should work:
INSERT INTO table2 SELECT * FROM table1 WHERE condition;
If the two tables do not have identical columns, then something like this should work:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT columnA, columnB, columnC, ...
FROM table1
WHERE condition;
I cribbed these directly from w3schools.com. You can search for many such examples using the search string "mysql select from one table into another".

SQL update to NULL using a variable

I keep having problems with quotes in relation to a table update. I'm sending a Post with several values from a form, and then update a table with them. For the code to work, I need to wrap keys with backslash ($ColumnaString), and values with single quotes ($ValueString). This works OK. My problem is that occasionally I want to update to NULL (when $value==""). But my present code don't do that. Can somebody spot the problem?
$id_tag=trim($_POST['id']);
foreach($_POST as $key=>$value){
if ($key!="UpdatePeople"){
$ColumnaString="`".$key."`";
$ValueString="'".iconv('UTF-8', 'ISO-8859-1//TRANSLIT', utf8_encode($value))."'";
if ($key=="In_Date" and $value=="") {$ValueString==NULL;} //Hereis my problem I think
$link->query("UPDATE MyTable SET ".$ColumnaString."=".$ValueString." WHERE `id`=".$id_tag."");
}
}
You could check $id_tag and create a proper part of sql code
$str = ($id_tag ='' ) ? ' is null ' : ' = '.$id_tag;
$link->query("UPDATE MyTable SET ".$ColumnaString." = ".$ValueString." WHERE `id`".str."");
and for $vale
if ($key=="In_Date" and $value=="") { $ValueString = 'NULL' ;} //Hereis my problem I think
check your database if the columns is defined as NOT NULL

Apostrophe causing problems with insert

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);

php insert data from fetch array to other table on version 5.4

I have moved to IIS 8 in PHP 5.4. I am trying to collect data from a table and insert them to a different one, i know my code is correct, but seems to be not working, probably because of the php version, can anyone help me?
here's my code
$query = odbc_exec($conn, "SELECT * FROM member");
while($rows = odbc_fetch_array($query)) {
$querystring = "INSERT INTO oldusers (username, password, regdate) VALUES ('$rows['userid']', '$rows['passwd']', '$rows['registdate']')";
$query2 = odbc_exec($conn, $querystring);
odbc_free_result($query2);
//echo $rows['userid']." ".$rows['passwd']." ".$rows['registdate']."<br>";
}
thanks in advance.
instead trying to insert one by one record, better to insert like below:
INSERT INTO oldusers (username, password, regdate) SELECT userid,passwd,registdate FROM member
for more information :http://dev.mysql.com/doc/refman/5.5/en/insert-select.html
You're placing $rows['passwd'] inside of a double-quoted string. Instead you should do:
$str = "some sql $rows[passwd] rest of sql"; // notice the absence of single quotes
or:
$str = "some sql {$rows['passwd']} rest of sql";
or (I think this way is most readable):
$str = 'some sql' . $rows[passwd] . ' rest of sql';
If your column contains text you'll need to add surrounding single quotes where necessary.
Having said all that, you should instead use parameterized queries (if your database supports it) as it's safer (from SQL injection). If that's unavailable you will at the very least need to escape the data before concatenating it to the string.

PHP - MySql : (String) put slash between 2 number

I've problem in my code, I use these lines for example:
$numb1 = 12;
$numb2 = 6;
$folder = (string)$numb1."/".$numb2;
echo ($folder); // => 12/6
$sql="insert into test (folder) values (".$folder.");
// Here the value of folder is "2" !!!
// Structure of the colume folder : varchar(50) utf8_general_ci
I went insert in this column "folder" the string output "12/6", but every time in database I get the division of $numb1 / $numb2, in this case I get "2";.
You should really be using mysqli. It's much more secure.
You're missing quotes around your string. SQL needs quotes to identify it as a string. Otherwise it uses as a number.
Where you say
insert into ... values(12/6)
It should be
Insert into ... Values '12/6')
Try:
"INSERT INTO test (folder)
VALUES ('".$folder."')";
"INSERT INTO test (folder)
VALUES (' ".$folder." ' )";

Categories