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

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.

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

Converting a string into array in phpGrid for inserting into postgresql

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

how to insert radio button values and dropdown values to database postgresql using php

I want to insert the data into postgresql database which includes radio button and dropdwn box. I tried 3 different insert queries.
1)
$query = sprintf("INSERT INTO onf VALUES('%s','%s','%s','%s','%s','%s','%d')",$_REQUEST['title'],$_REQUEST['name'],$_REQUEST['district'],$_REQUEST['rurban'],$_REQUEST['taluk'],$_REQUEST['village'],$_REQUEST['wardno']);
2)
$qry="INSERT INTO onf(title, name, district,rurban,taluk,village,wardno) VALUES ('$tile', '$name', '$district','$rurban','$taluk','$village','$wardno')";
3)
$qy="INSERT INTO onf(title, name, district,rurban,taluk,village,wardno) VALUES (('$_POST[title]','gen','$_POST[gen]),'$_POST[name]','$_POST[district]','$_POST[rurban]','$_POST[taluk]','$_POST[village]','$_POST[wardno]')";
$res = pg_query($db,$qy);
My problem is in 1st query oly name alone gets inserted and in 2nd , 3rd no record gets inserted. Y dropdown nd radio button is not inserting into database?
Tanx in advance..
May just be because neither of those 3 is proper PHP code.
Query 1:
Don't use $_REQUEST. Use $_POST.
Query 2:
Unless you have register_globals turned on, which I SERIOUSLY hope you don't, your vars ($tile, $name, etc.) will not contain the information submitted by the form. Again, you want to use $_POST.
Query 3:
Your variables aren't properly escaped. Generally, I recommend not embedding variables into double-quoted strings if you don't quite have a grasp on string concatenation in PHP. Use single-quoted strings and build them by breaking the string and concatenating with ..
Now, I feel like your second query is the closest to what you want, so try this:
$qry = '
INSERT INTO onf (
title,
name,
district,
rurban,
taluk,
village,
wardno
) VALUES (
"'.$_POST['tile'].'",
"'.$_POST['name'].'",
"'.$_POST['district'].'",
"'.$_POST['rurban'].'",
"'.$_POST['taluk'].'",
"'.$_POST['village'].'",
"'.$_POST['wardno'].'"
);
';

data no inserting into mysql database due to difference in 'quotes'

I am having a very strange problem inserting values into my mysql database, using php, so i was running a test, the simplest of the simple insert; the following doesnt work:
<?php
include("config.php"); // put the *FULL* path to the file.
mysql_query("INSERT INTO 'lms'.'test2' ('trn') VALUES ('17')");
?>
However the following works:(Note the difference in single quotes)
<?php
include("config.php"); // put the *FULL* path to the file.
mysql_query("INSERT INTO `lms`.`test2` (`trn`) VALUES ('17')");
?>
I really can't see what the problem is could I get sum assistance please
You don't need to encapsulate tables within a query unless they have space or they are reserved words.
INSERT INTO 'lms'.'test2' ('trn') VALUES ('17')
// This makes no real sense to the db. It should be:
INSERT INTO lms.test2 (trn) VALUES ('17')
If the column trn accepts numbers, it really should be:
INSERT INTO lms.test2 (trn) VALUES (17)
With MySQL, you can use the tilted quote character to encapsulate names, but not strings. To enter a string in the query you will have to use normal quotes like '.
You can to this:
select `someTable`.`someColumn` from `someTable`
but not this:
select someTable.someColumn from someTable where myName=`Tommy`;
The correct use would be:
select someTable.someColumn from someTable where myName='Tommy';

mysql query does not work on different files -php

i might be doing some idiot mistake, but i could not figure that out. i have some values coming from html and wanna insert into mysql db. problem is, the very same query does not work in regular php file (that includes other queries), but when i try on an independent php file, it does. here is a sample of the code:
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15);
as i mentioned, the very same code works when i just copy this snippet to a new php file, and it works smoothly.. as you see, there are 20+ insert with the same php, because there are 25+ tables, but data is not much. first 14 query and following 7 queries do work by the way.
do you have any ideas?
There are some things to check and do.
Sanitize user input:
"('$article_id', '".mysql_real_escape_string($_POST['Article_Title'])."')";
You might also want to check if the value is what you expect.
Is your $article_id correct for column Article_ID?
Are your table and column names correct?
Check for errors:
$res = mysql_query($sql15);
if (!$res)
echo mysql_errno($link) . ": " . mysql_error($link);
Show us you complete query:
echo $sql15;
First of all i would suggest you to write your insert query like below
$sql15="insert into body SET Article_ID = '$article_id', Article_Title = '".$_POST['Article_Title']."'";
echo $sql15;
mysql_query($sql15);
so that each time when you add new column to database it would be easy for u to change insert query. echo your query and see it in browser. in it seems to o.k then copy it and paste it in SQL section under your phpmyadmin (see you are choosing proper database) and run it. if one row inserted successfully then your query is alright.
I hope this would help you a little.
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '".$_POST['Article_Title']."') ";
mysql_query($sql15) or die(mysql_error());
use like this u will be get the error. then u will be find the issue
I think using mysql_real_escape_string may solve your problem.I also recommend you to store your form data in a string.
$article_title= mysql_real_escape_string($_POST['Article_Title']);
$sql15="insert into body
(Article_ID, Article_Title)
values
('$article_id', '$article_title') ";
mysql_query($sql15) or die(mysql_error());

Categories