Converting a string into array in phpGrid for inserting into postgresql - php

I am trying to insert a string into an integer array using phpGrid with a PostgreSQL database. I had to convert the array to a string to remove the brackets when displaying data inside the grid for viewing, but when I try to convert the string back into an array upon adding a field, it is not converting to the format {1,2,3,4}. I'm using the string_to_array function that PostgreSQL offers to do so. Here is the code I am using:
$dg = new C_DataGrid("SELECT array_to_string(field, ', ') as field_to_string FROM tblname");
This works as expected (removes the { } from the data being displayed) but when I try to insert, this query looks like this:
INSERT INTO tblname (field_to_string) VALUES ('1,2,3,4');
and this is what I am trying to insert (convert to array)
$arrFields['field_to_string'] = "string_to_array('" . $arrFields['field_to_string'] . "', ',')";
$sqlCrud = $db->db->GetInsertSQL($rs, $arrFields, get_magic_quotes_gpc(), true);
Any help would be appreciated.
Thanks.

Can you echo sqlCrud and find out the SQL Insert statement by setting its DEBUG set to true? It's likely the Insert statement has an error during conversion.
Your PostgreSql should be something similar to the following:
INSERT INTO tblname(field_to_string) VALUES ('{1,2,3,4}'::varchar[])
You can check out PostGreSql with array to string conversion examples here: http://www.postgresonline.com/journal/archives/228-PostgreSQL-Array-The-ANY-and-Contains-trick.html

Related

Where does SQL output values when OUTPUT clause is used in PHP string variable?

I am trying to retrieve an auto-incremented value that is created upon insertion. This ID value will be used in a SELECT statement later, so it would be nice to know what it is when I insert instead of writing another query. The problem is that I don't know where OUTPUT clause outputs it. The query is in the form of a PHP string variable.
I'm new to SQL and PHP, so I'm not really sure what to try. I just need some help understanding.
$query = "INSERT INTO Table1 (orderNumber, revisionNumber, creationDate...)"
. " OUTPUT Inserted.ID"
. " VALUES (blah, blah, blah...)";
execute_query($query);

Storing & retrieving complex data to MySQL BLOB to retrieve data in same state prior to encode & DB insertion using PHP

I am building a function that is inserting complex data into a MySQL table to be used as a queue for a CSV file creation. Without going into explicit details, what I want is simply to convert an array into serialized format using json_encode, insert it to a MySQL table with a prepared statement, and then retrieve that data, json_decode, and have the original data in the exact same form it was prior to insertion.
The code as it stands looks something like this:
// Array data previously created
foreach ( $array as $key => $element ) {
$array[$key] = htmlspecialchars($element,ENT_QUOTES);
}
$this->db->query("UPDATE `table` SET `blob_field` = '".$this->db->escape($array)."' WHERE `id` = '".(int)$id."'");
Then I retrieve the data using:
$decoded_array = $this->db->query("SELECT `blob_field` FROM `table` WHERE `id` = '".(int)$id."'")->row['blob_field'];
$decoded_array = json_decode($decoded_array);
$decoded_array = array_map('htmlspecialchars_decode',$decoded_array);
// Add to CSV using fputcsv standard process
The resulting CSV is about 99.9% perfect. But when opened in Excel about 0.1% of the rows have columns that are jumping where they should not. Furthermore, every instance of \r\n appears to be getting replaced with the Windows newline character.
My question is... what am I doing wrong? Why are the newline characters being replaced with the Windows equivalent, and why does the CSV look messed up when opened in Excel?

Selecting a string with an Ampersand in it with php on a postgres database

I'm working on a group project from school which requires selecting from a Postgres database with php.
I tested my queries on the psql dbms before trying them in the php interface. This is my test query:
SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf & Grendel';
The query does return the information from the database I need, however when using this in php it returns nothing.
pg_last_error() says nothing.
In what way can I ensure that I can select titles with ampersands(&) in them?
I've tried seperating the string and putting them back together with sql code:
SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf '||chr(38)||' Grendel'
I've tried escaping the string
This is an example of some of my php code:
$query = 'SELECT m.movieid, m.tomatourl FROM movies m WHERE title = $1';
pg_prepare($conn, "getmovie", $query) or die(pg_last_error());
$result = pg_execute($conn, "getmovie", $i) or die("Query failed: ". pg_last_error());
$movie = pg_fetch_array($result, NULL, PGSQL_BOTH);
This will work as long as the string in the $i array does not have an ampersand in it.
I would just change the database to not have an ampersand, but I don't really have control over it.
Is there some way to do a select statement like this using the php postgres functions?
The problem seems to have been caused by the the quotes that are around the string that passed in to the sql, by passing the string directly through the prepared statement it is like this "Beowulf & Grendel"
when it has to be passed to the database like this 'Beowulf & Grendel'
It also seems that even though it wasn't showing in var_dump() directly in the string printout it
was actually sending it as this SELECT m.movieid, m.tomatourl FROM movies m WHERE title = 'Beowulf & Grendel'; The the only thing that gives it away it the character count in the var_dump and not the printout of the string. The fix for this was to do html_entity_decode() on the title passed in.
Special thanks to DarkBee and Daniel Verite for helping solve this issue.

How can I send a PHP variable array to a MySQL database?

So I have a variable array created from scraping a plaintext data string from a webpage (using Simple HTML DOM Parser class). This variable is the formatted to make it more concise and useful.
I now wish to export this data into a MySQL table where the table name is the webpage title (scraped separately) and the data input is an array, where each word extracted from the webpage is a separate data record.
Here is my code (where $trimmed is a formatted variable string of data scraped from a user input webpage):
$trimmed->plaintext=trim($trimmed->plaintext);
$array = (explode(" ", $trimmed->plaintext));
$printarray = print_r ($array);
mysql_select_db("test", $connect) or die ('Could not find database.');
$sql = "CREATE TABLE '$title'";
$myquery = sprintf("INSERT INTO WebPage '%s'
VALUES '%s'",
mysql_real_escape_string($title->plaintext),
mysql_real_escape_string($printarray));
$result = mysql_query($myquery);
if (!$result) {
$message = '<br /><br /><br /> Invalid query: ' . mysql_error() . "\n";
$message .= '<br /><br /> Whole query entered here: ' . $myquery;
die($message);
}
The error is recieve when trying this is:
Invalid query: 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 ''Example Domain' VALUES '1'' at line 1
Whole query entered here: INSERT INTO WebPage 'Example Domain' VALUES '1'
I can provide more code if needed, and sorry in advance if I haven't explained this very well; I am quite new to this.
Thanks in advance.
Your SQL:
INSERT INTO WebPage 'Example Domain' VALUES '1'
is not valid. Maybe you meant:
INSERT INTO `WebPage` ('Example Domain') VALUES ('1')
On a side note, if Example Domain is indeed a column name: you should really avoid spaces in field's names.
There are lot's of errors here.
First, The SQL you're generating for the insert looks incorrect:
INSERT INTO tableName (fields) VALUES (values)
Your code says:
INSERT INTO WebPage 'plainText' VALUES (array)
You should remove Webpage if you want to create a table named like the webpage title. Plus, it must be a single word (replace empty spaces with something like '_').
Second, you need to create the table. You need the proper CREATE TABLE structure prior to doing the insert.
Third, your echo print_r won't work for inserting a value per field (column). You need to iterate the array and for each key insert a value. But you should had already done this for creating the table columns.
It looks as if you are trying to incorporate the output from print_r in your query. This isn't possible as print_r is a function that outputs data from an array to the page.
In order to store the contents of an array in the database you can use json_encode to convert the array to a string. Then use json_decode when retrieving it so change it back into a php array.
E.g.
$myquery = sprintf("INSERT INTO `WebPage` ('%s')
VALUES ('%s')",
json_encode($title->plaintext),
json_encode($array)); //not $printarray as that is not an actual array
edit: As others have noted, mysql_real_escape_string is a deprecated function so other methods should be used to escape characters.
edit2: serialize could also be used in place of json_encode although I am not sure of the relative advantages/disadvantages. A more ideal method would be to restructure your database table to accommodate all contents of the array as a separate piece of data although this may sometimes not be practical.

bar/pipe delimited field

Anyone know how to insert bar/pipe delimited array in an array field?
With comma its working but when I change it to bar it produces error "malformed array literal"
example (works):
insert into table (arrayfield) values ('{"var1","var2","var3"}')
example (doesn't work):
insert into table (arrayfield) values ('{"var1"|"var2"|"var3"}')
btw i'm using postgres 8.2 and PHP and i can't use comma as delimiter for various reasons.
If you can use values without quotes because you know that no pipe is in your data, then you can use:
insert into table (arrayfield) select string_to_array('var1|var2|var3','|');
If you need that your values are quoted on your pipe-delimited string then it gets complicated. If that's the case then I think you should format and quote properly your array using ARRAY['val1','val2','val3'] syntax in PHP.

Categories