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

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." ' )";

Related

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

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

$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`";

Error putting data into database

I have the following php code:
foreach($html->find('dl[class=movie-info]') as $info) {
for($i = 0; $i <= 20; $i++) {
$contenido = $info->find('dt',$i)->plaintext;
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);}}}
(the code has more if functions)
And a mysql table where I put the content of the variables....
The problem is with the $year content, I need to fill it in a smallint(5) unsigned.
When I use
$con = mysqli_connect("localhost","root","tdguchiha","phpbb3");
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero')");
mysqli_close($con);
All the content is inserted, but when i try to insert $year into año with type smallint(5) unsigned nothing happens, no row is created...
how can I convert $year to a number (it must be a number) to fill it in that column? or I need to change the column type?
PD: I am learning right now to "play" with mysql
thanks
There is no difference in mysql between a number and a string when doing queries. Make sure you include the column name in the list of all the columns:
mysqli_query($con,"INSERT INTO pablo (forum_id, calidad, titulo, caratula, sinopsis, pais, director, reparto, genero, year) VALUES ('$forum_id', '$calidad', '$titulo', '$img', '$sinopsis', '$pais', '$director', '$reparto', '$genero', '$year')");
^notice year the column ^now the actual value
Just replace year in the column section with the name of your mysql column.
Perhaps try casting it to an integer instead of using utf8_encode:
$year = intval($info->find('dd',$i)->plaintext);
Or, in addition to it:
$year = intval(utf8_encode($info->find('dd',$i)->plaintext));
Can you give us an example of the data?
EDIT: Damien is right, intval() shouldn't make a difference.
Try echoing out the contents instead, and making sure it's an actual number in the string to do some debugging:
if($contenido == 'Año'){
$year = utf8_encode($info->find('dd',$i)->plaintext);
echo $year.'<br />';}}}
Before posting a question to StackOverflow, identify any error-codes / error-messages and post them with your question:
/* check connection */
if ( mysqli_connect_errno() ) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
And:
if ( ! mysqli_query( $link, "SELECT ..." )) {
printf("Errorcode: %d\n", mysqli_errno($link));
}
More on the PHP doc site.
I think your problem is with value type and data you are trying to insert:
A smallint is between -32768 and 32767 signed, or 0 and 65535 unsigned.
The (5) represents the display width of the field - if you will try to put 90000 you will be rejected.
In your case it should not be a problem (years value I assume) but show us the data you are trying to insert.
I guess that you are parsing some content using simple_html_dom - make sure all data retrieved is
as you expect before inserting it to DB.
Also: Try changing the type to int(5) and now tell us....
It will be easier to see the query you use (with the year) and a sample of data.
For error loging and display use:
$execute = mysqli_query($con,"INSERT INTO pablo ( ....your query..... ")
or
printf("Errormessage: %s\n", mysqli_error($con));
Have Fun

Insert a web page in mssql table

i want to insert a web page (text format) in a table
When i do my query, it gives me a mistake. But when i remove the webpage (in a string), it works.
The variable is the $comment one.
The row for message is text (not varchar(255))
$query_insert = "INSERT INTO [".$project."_spec].[IsMessage] (project, message, note) VALUES('".$project."', '".$comment."', '".$note."')";
mssql_query($query_insert) or die(mssql_get_last_message() . "[ " . $query_insert . " ]");
Is there a way to convert HTML in text?
Thanks
Your are building your SQL code dynamically by injecting variables with random contents into your query:
$query_insert = "INSERT INTO ... VALUES('".$project."', '".$comment."', '".$note."')";
^^^^^^^^ ^^^^^^^^ ^^^^^
This way, it won't take long until you build an invalid query inadvertently:
$project = "Foo";
$comment = "It isn't ready yet";
$note = "See John's notes";
$query_insert = "INSERT INTO ... VALUES('".$project."', '".$comment."', '".$note."')";
var_dump($query_insert);
// string(71) "INSERT INTO ... VALUES('Foo', 'It isn't ready yet', 'See John's notes')"
^ ^
Start string | | End string... oops
I haven't used the legacy MSSQL extension so I don't know how you're supposed to fix this (apparently, you cannot!) but there's a user comment that proposes a custom function. You should drop the stripslashes() call but the rest looks correct (without actually having tested it).
If you happen to use Windows and it's not too late for a change, the newer SQLSRV provides a better feature set.

PHP to PostgreSQL insert unnested arrays into multiple rows

I have some data in PHP arrays/variables ready to insert into a PostgreSQL table via an INSERT statement.
For a simple example say I have the following information:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
(In my real application these are double precision and potentially 1,000+ values)
I also have my postgresql table with columns "name","time","elevation"
I want to insert these in a single INSERT statement, and have been given multiple different ways to do this.
Loop and insert one data point (row) at a time.
Use unnest() on the arrays and do a single insert (fastest)
My question is can I pass a single variable name, and the un-nested arrays and have name repeated every row (ever array element), or do I need to construct a repeated array for name the equivalent count() as the other arrays?
An example statement:
*cr_query is a custom PHP pg_query wrapper we use
cr_query($conn,"INSERT INTO sometable (name,time,elevation) VALUES ({$name},{unnest($time)},{unnest($elevation)}););
This would insert into sometable:
ID name time elevation
1 someName 1 100
2 someName 2 200
3 someName 3 300
Am I correct here or do I need to do something else?
EDIT:
Lets say I also have another variable "surface". Surface can be a double value or can be NULL. So I want to insert into the table to look like so:
ID name time elevation surface
1 someName 1 100 50
2 someName 2 200 NULL
3 someName 3 300 100
In PHP, using the method perscribed by klin below an array for surface in the unnest statement would become unnest(array[50,,100]); This throws an error like so:
(Error from my real data)
ERROR: syntax error at or near "," LINE 3: ...-6,5.75E-6,5.75E-6,5.75E-6,5.75E-6]),unnest(array[,,,,,,,,,]... ^
EDIT 2:
Now that all of the "encoding" is working a new problem has popped up. Say the example column "surface" above is type double precision.
Say I am inserting an array, but for this set all of the data is null.
The essential piece is:
unnest(array[null,null,null,null,null,null,null,null,null,null])
However, this array is of type string. Add a single value to it and it becomes the type of that numeric value, but I need to be able to handle this.
My question is: How do I insert an unnested array of all null values into a double precision column? (I tried to cast ::double precision) but it's not possible.
Assuming your cr_query() function is not doing any magic things, your code is going to raise postgres syntax error. You can use unnest but you must prepare proper query text.
Try your code:
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
echo "INSERT INTO sometable (name,time,elevation) VALUES ".
"({$name},{unnest($time)},{unnest($elevation)})"
echo: INSERT INTO sometable (name,time,elevation) VALUES (someName,{unnest(Array)},{unnest(Array)})
Obviously it is not what we want to send to postgres. How to repair this?
$name= 'someName';
$time = array(1,2,3);
$elevation = array(100,200,300);
$timestr = 'array['. implode(',', $time). ']';
$elevstr = 'array['. implode(',', $elevation). ']';
echo "INSERT INTO sometable (name,time,elevation) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr));"
echo: INSERT INTO sometable (name,time,elevation) VALUES ('someName',unnest(array[1,2,3]),unnest(array[100,200,300]));
I think this is correct query. Note that I enclosed text variable '$name' in single quotes.
If you have nulls in your arrays you have to replace all empty strings to 'null' in prepared text for query.
Probably the simplest way to do it is to use str_replace().
As the conversion is getting more complicated it is handy to write a function (say "pgstr()") for that purpose.
function pgstr($array) {
$str =
str_replace('[,', '[null,',
str_replace(',]', ',null]',
'array['. implode(',', $array). ']'));
while (strpos($str, ',,') > 0) $str = str_replace(',,', ',null,', $str);
return $str;
}
$name= 'someName';
$time = array(1,2,3,4);
$elevation = array(100,null,300,null);
$surface = array(null,null,3.24,null);
$timestr = pgstr($time);
$elevstr = pgstr($elevation);
$surfstr = pgstr($surface);
echo
"INSERT INTO sometable (name,time,elevation,surface) ".
"VALUES ('$name',unnest($timestr),unnest($elevstr),unnest($surfstr));";

Categories