How to store an array into a table? - php

I'm trying to store an array into a table but its not working it adds the table but it doesn't add the column name at all. It's just empty
Here's the entire code.
<?php
include 'db.php';
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
if(isset($_GET['TYPE'])) {
file_put_contents('contents.txt', $_GET['TYPE'] . "\n", FILE_APPEND);
}
if(isset($_GET['ISEXPLORED'])) {
file_put_contents('contents.txt', $_GET['ISEXPLORED'] . "\n", FILE_APPEND);
}
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name VARCHAR(30), Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition VARCHAR(30), guid VARCHAR(30))");
}
if(isset($_GET['GUID'])) {
file_put_contents('contents.txt', $_GET['GUID'] . "\n", FILE_APPEND);
}
print('Added!');
?>
'RESOLVED THANKS TO ECHO'
'move the code of creating table first then insert to that table. you are inserting then creating table , you should do the opposite.'
Problem 2
Hey guys. I'm having an issue when I do
/test/test.php?SECTORPOSITION=13137&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 I get a syntax error.
But when I do
?SECTORPOSITION=hey&NAME=hibb&TYPE=Cluster&ISEXPLORED=true&GUID=13 It works fine?
Here's my code.
<?php
include 'db.php';
if(isset($_GET['SECTORPOSITION'])) {
mysql_query("CREATE TABLE `".$_GET['SECTORPOSITION']."` ( Name INT, Type VARCHAR(30), IsExplored VARCHAR(30), SectorPosition INT, guid INT)");
}
if(isset($_GET['TYPE'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$type= mysql_real_escape_string($_GET['TYPE']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
$isexplored = mysql_real_escape_string($_GET['ISEXPLORED']) ; // escape your variable here
$guid = mysql_real_escape_string($_GET['GUID']) ; // escape your variable here
mysql_query("INSERT INTO $sector (Name,Type,IsExplored,SectorPosition,guid) VALUES ('$name','$type','$isexplored','$sector','$guid') ") or die(mysql_error()) ;
}
print('Added!');
?>

you can do like this
look like I have an array
$array = array(1,2,3,4);
json_encode($array);
and save the json encoded value
Its not standard to store array in db. You could see any cms, they would store it as json encoded objects, so that they can retrieve back the values

Dont use mysql_ functions anymore (its a sin!), use the improved. Use mysqli_. Like this:
$con = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_GET['NAME'])) {
$your_table_whitelist = array('table1', 'table2'); // list your tables
if(!in_array($_GET['SECTORPOSITION'], $your_table_whitelist, true)) {
exit; // no table like that found
}
$stmt = $con->prepare("INSERT INTO {$_GET['SECTORPOSITION']} (Name) VALUES(?)");
$stmt->bind_param('s', $_GET['NAME']);
$stmt->execute();
}
Things to point out:
your current code is open to SQL injections, use MYSQLI and utilize parameterized queries instead.
since you cannot bind tables inside, just create a whitelist of table to compare to your variable which will hold the table name. If it matches, its okay, it's not, just handle that error.

your code is very open to sql injection you should go to mysqli or pdo.
if(isset($_GET['NAME'])) {
$sector = mysql_real_escape_string($_GET['SECTORPOSITION']) ; // escape your variable here .
$name = mysql_real_escape_string($_GET['NAME']) ; // escape your variable here .
mysql_query("INSERT INTO $sector (Name) VALUES ('$name') ") or die(mysql_error()) ;
}
EDIT: you got this error
Table 'TheGalaxy.at' doesn't exist
because you are creating table after the insert , so the table is not created yet.

Please do not use mysql function as they're deprecated, instead use mysqli.
the proper way to insert data into the database as follows :
mysqli_query($link, "INSERT INTO tableName values('".$_GET['NAME']."')");
where $link is your connection string. like
$link = ("myhost","myUser","myPassword","myDB");
Hope this will help.

if(isset($_GET['NAME'])) {
$sql= "INSERT INTO ".$_GET['SECTORPOSITION']."(name) VALUES(".$_GET['NAME'].")";
mysql_query($sql);
}

Related

php - bind_param inside foreach() not correctly passing

I'm sure this is a duplicate, but I've tried several different things on the site here and none of them are working for me. I'm calling my function in php, sending $mysqli connection, the $clientID, and the array of $tagFields to upload.
It's 'working', but the values are always null. I've put echo "$tagName" inside the foreach, and it's reading it, but not sending it up to the database. $clientID, however, IS passing information. So basically all it does is upload consistently blank rows into my database. What am I doing wrong here?
function tagRefresh($mysqli,$clientID,$tagFields) {
$stmt = $mysqli->stmt_init();
$query = "INSERT INTO client_tags (client_id,tag_category) VALUES (?,?) ";
$stmt->prepare($query);
foreach($tagFields as $tagName) {
$stmt->bind_param('is',$clientID,$tagName);
$stmt->execute();
}
}
some sample values for $tagFields:
$tagFields[0] = "Regional";$tagFields[1] = "Automotive";$tagFields[2] = "Maintenance";
Note mysqli_stmt::bind_param bind the reference of the variables.
Try the below:
function tagRefresh($mysqli,$clientID,$tagFields) {
$stmt = $mysqli->stmt_init();
$query = "INSERT INTO client_tags (client_id,tag_category) VALUES (?,?) ";
$stmt->prepare($query);
$stmt->bind_param('is', $clientID, $tagName);
foreach($tagFields as $tagName) {
$stmt->execute();
}
}
execute() shouldn't be situated inside the foreach.
Among with a myriad of problems associated with the database (including the client_id being the primary key), I've rebuilt the formula like this:
function tagRefresh($mysqli,$clientID,$tagFields) {
$query = "DELETE FROM client_tags WHERE client_id = '" . $clientID . "'"; //we have to delete the old ones every time
if(!$mysqli->query($query)) {
echo $mysqli->error;
}
if($tagFields != '') { //see if data was sent
$tags = array();
foreach($tagFields as $tag) {
$tags[] = "('" . (int) $clientID . "', '" . $tag ."')"; //build an array
}
$query = "INSERT INTO client_tags (client_id,tag) VALUES " . implode(',', $tags) . " ON DUPLICATE KEY UPDATE client_id = " . $clientID;
if(!$mysqli->query($query)) {
echo $mysqli->error; //drop errors, will attach this later
}
}
}
This formats to something like this:
INSERT INTO client_tags (client_id,tag) VALUES ('1234','mechanical'),('1234','regional'),('1234','service') ON DUPLICATE KEY UPDATE client_id = '1234';
The ON DUPLICATE part is important because for some reason the client_id is set to primary key. I'm gonna have to talk to the app guys and see if this matters to them.
Unfortunately, bind_param isn't being used, but this is a admin panel access only for company employees only, and now that this is working I'm giving them autocomplete boxes to reference existing values.

PDO PHP insert into DB from an associative array

I have an array like this
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
When I do a var-dump I get this ->
{ ["phone"]=> int(111111111) ["image"]=> string(19) "sadasdasd43eadasdad" }
Now I am trying to add this to the DB using the IN statement -
$q = $DBH->prepare("INSERT INTO user :column_string VALUES :value_string");
$q->bindParam(':column_string',implode(',',array_keys($a)));
$q->bindParam(':value_string',implode(',',array_values($a)));
$q->execute();
The problem I am having is that implode return a string. But the 'phone' column is an integer in the database and also the array is storing it as an integer. Hence I am getting the SQL error as my final query look like this --
INSERT INTO user 'phone,image' values '111111111,sadasdasd43eadasdad';
Which is a wrong query. Is there any way around it.
My column names are dynamic based what the user wants to insert. So I cannot use the placeholders like :phone and :image as I may not always get a values for those two columns. Please let me know if there is a way around this. otherwise I will have to define multiple functions each type of update.
Thanks.
Last time I checked, it was not possible to prepare a statement where the affected columns were unknown at preparation time - but that thing seems to work - maybe your database system is more forgiving than those I am using (mainly postgres)
What is clearly wrong is the implode() statement, as each variable should be handled by it self, you also need parenthesis around the field list in the insert statement.
To insert user defined fields, I think you have to do something like this (at least that how I do it);
$fields=array_keys($a); // here you have to trust your field names!
$values=array_values($a);
$fieldlist=implode(',',$fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="insert into user($fieldlist) values(${qs}?)";
$q=$DBH->prepare($sql);
$q->execute($values);
If you cannot trust the field names in $a, you have to do something like
foreach($a as $f=>$v){
if(validfield($f)){
$fields[]=$f;
$values[]=$v;
}
}
Where validfields is a function that you write that tests each fieldname and checks if it is valid (quick and dirty by making an associative array $valfields=array('name'=>1,'email'=>1, 'phone'=>1 ... and then checking for the value of $valfields[$f], or (as I would prefer) by fetching the field names from the server)
SQL query parameters can be used only where you would otherwise put a literal value.
So if you could see yourself putting a quoted string literal, date literal, or numeric literal in that position in the query, you can use a parameter.
You can't use a parameter for a column name, a table name, a lists of values, an SQL keyword, or any other expressions or syntax.
For those cases, you still have to interpolate content into the SQL string, so you have some risk of SQL injection. The way to protect against that is with whitelisting the column names, and rejecting any input that doesn't match the whitelist.
Because all other answers allow SQL injection. For user input you need to filter for allowed field names:
// change this
$fields = array('email', 'name', 'whatever');
$fieldlist = implode(',', $fields);
$values = array_values(array_intersect_key($_POST, array_flip($fields)));
$qs = str_repeat("?,",count($fields)-1) . '?';
$q = $db->prepare("INSERT INTO events ($fieldlist) values($qs)");
$q->execute($values);
I appreciated MortenSickel's answer, but I wanted to use named parameters to be on the safe side:
$keys = array_keys($a);
$sql = "INSERT INTO user (".implode(", ",$keys).") \n";
$sql .= "VALUES ( :".implode(", :",$keys).")";
$q = $this->dbConnection->prepare($sql);
return $q->execute($a);
You actually can have the :phone and :image fields bound with null values in advance. The structure of the table is fixed anyway and you probably should got that way.
But the answer to your question might look like this:
$keys = ':' . implode(', :', array_keys($array));
$values = str_repeat('?, ', count($array)-1) . '?';
$i = 1;
$q = $DBH->prepare("INSERT INTO user ($keys) VALUES ($values)");
foreach($array as $value)
$q->bindParam($i++, $value, PDO::PARAM_STR, mb_strlen($value));
I know this question has be answered a long time ago, but I found it today and have a little contribution in addition to the answer of #MortenSickel.
The class below will allow you to insert or update an associative array to your database table. For more information about MySQL PDO please visit: http://php.net/manual/en/book.pdo.php
<?php
class dbConnection
{
protected $dbConnection;
function __construct($dbSettings) {
$this->openDatabase($dbSettings);
}
function openDatabase($dbSettings) {
$dsn = 'mysql:host='.$dbSettings['host'].';dbname='.$dbSettings['name'];
$this->dbConnection = new PDO($dsn, $dbSettings['username'], $dbSettings['password']);
$this->dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
function insertArray($table, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$sql="INSERT INTO `".$table."` (".$fieldlist.") VALUES (${qs}?)";
$q = $this->dbConnection->prepare($sql);
return $q->execute($values);
}
function updateArray($table, $id, $array) {
$fields=array_keys($array);
$values=array_values($array);
$fieldlist=implode(',', $fields);
$qs=str_repeat("?,",count($fields)-1);
$firstfield = true;
$sql = "UPDATE `".$table."` SET";
for ($i = 0; $i < count($fields); $i++) {
if(!$firstfield) {
$sql .= ", ";
}
$sql .= " ".$fields[$i]."=?";
$firstfield = false;
}
$sql .= " WHERE `id` =?";
$sth = $this->dbConnection->prepare($sql);
$values[] = $id;
return $sth->execute($values);
}
}
?>
dbConnection class usage:
<?php
$dbSettings['host'] = 'localhost';
$dbSettings['name'] = 'databasename';
$dbSettings['username'] = 'username';
$dbSettings['password'] = 'password';
$dbh = new dbConnection( $dbSettings );
$a = array( 'phone' => 111111111, 'image' => "sadasdasd43eadasdad" );
$dbh->insertArray('user', $a);
// This will asume your table has a 'id' column, id: 1 will be updated in the example below:
$dbh->updateArray('user', 1, $a);
?>
public function insert($data = [] , $table = ''){
$keys = array_keys($data);
$fields = implode(',',$keys);
$pre_fields = ':'.implode(', :',$keys);
$query = parent::prepare("INSERT INTO $table($fields) VALUES($pre_fields) ");
return $query->execute($data);
}

Why can't php variables be used as the table name in mysql insert statement

In my PHP script I am trying to use variable name as the table name in a MySQL statement, but when I use the variable as the table name it give me a syntax error if no ` are used and says Incorrect Table Name '' when ` are used. The code is attached below
function toQuery($tblName){
$t = "testtitle";
$art = "testarticle";
$auth = "testauthor";
return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
}
mysql_connect("localhost","testuser","pass123");
mysql_query("Use `test_schema`");
if(mysql_query(toQuery("test_table"))){
echo "Query: ".toQuery("test_table")." was run.";
}else{
echo "Query: ".toQuery("test_table")." was not run. ".mysql_error();
}
When I use the variable $tblName variable it echos an identical query to if i just put test_table straight in the query returned, but the one with out the variable in query executes properly.
you don't use mysql_select_db() . try this :
function toQuery($tblName){
$t = "testtitle";
$art = "testarticle";
$auth = "testauthor";
return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
}
mysql_connect("localhost","testuser","pass123");
mysql_select_db('dbname');
mysql_query("Use `test_schema`");
if(mysql_query(toQuery("test_table"))){
echo "Query: ".toQuery("test_table")." was run.";
}else{
echo "Query: ".toQuery("test_table")." was not run. ".mysql_error();
}
replace your database name eith dbname
I think You are choosing the database outside the function. It might be because of the variable accessibility.
Try putting the line mysql_query("Usetest_schema"); inside function.
function toQuery($tblName){
$t = "testtitle";
$art = "testarticle";
$auth = "testauthor";
mysql_query("Use `test_schema`");
return "INSERT INTO `$tblName` VALUES ('$t', '$art', '$auth', null)";
}

Inserting multiple rows in a table using PHP

I am trying to insert multiple rows into MySQL DB using PHP and HTML from. I know basic PHP and searched many examples on different forums and created one script however it doesn't seem working. Can anybody help with this. Here is my script:
include_once 'include.php';
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
}
$sql .= "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES ('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
$result = mysql_query($sql, $con);
if (!$result) {
die('Error: ' . mysql_error());
} else {
echo "$row record added";
}
MySQL can insert multiple rows in a single query. I left your code as close as possible to the original. Keep in mind that if you have a lot of data, this could create a large query that could be larger than what MySQL will accept.
include_once 'include.php';
$parts = array();
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
$parts[] = "('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
}
$sql = "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES " . implode(', ', $parts);
$result = mysql_query($sql, $con);
Please try this code. Mysql query will not accept multiple insert using php. Since its is a for loop and the values are dynamically changing you can include the sql insert query inside the for each loop. It will insert each rows with the dynamic values. Please check the below code and let me know if you have any concerns
include_once 'include.php';
foreach($_POST['vsr'] as $row=>$vsr) {
$vsr=mysql_real_escape_string($vsr);
$ofice=mysql_real_escape_string($_POST['ofice'][$row]);
$date=mysql_real_escape_string($_POST['date'][$row]);
$type=mysql_real_escape_string($_POST['type'][$row]);
$qty=mysql_real_escape_string($_POST['qty'][$row]);
$uprice=mysql_real_escape_string($_POST['uprice'][$row]);
$tprice=mysql_real_escape_string($_POST['tprice'][$row]);
$sql = "INSERT INTO maint_track (`vsr`, `ofice`, `date`, `type`, `qty`, `uprice`,
`tprice`) VALUES ('$vsr','$ofice','$date','$type','$qty','$uprice','$tprice')";
$result = mysql_query($sql, $con);
if (!$result)
{
die('Error: ' . mysql_error());
}
else
{
echo "$row record added";
}
}
I would prefer a more modern approach that creates one prepared statement and binds parameters, then executes within a loop. This provides stable/secure insert queries and avoids making so many escaping calls.
Code:
// switch procedural connection to object-oriented syntax
$stmt = $con->prepare('INSERT INTO maint_track (`vsr`,`ofice`,`date`,`type`,`qty`,`uprice`,`tprice`)
VALUES (?,?,?,?,?,?,?)'); // use ?s as placeholders to declare where the values will be inserted into the query
$stmt->bind_param("sssssss", $vsr, $ofice, $date, $type, $qty, $uprice, $tprice); // assign the value types and variable names to be used when looping
foreach ($_POST['vsr'] as $rowIndex => $vsr) {
/*
If you want to conditionally abort/disqualify a row...
if (true) {
continue;
}
*/
$ofice = $_POST['ofice'][$rowIndex];
$date = $_POST['date'][$rowIndex];
$type = $_POST['type'][$rowIndex];
$qty = $_POST['qty'][$rowIndex];
$uprice = $_POST['uprice'][$rowIndex];
$tprice = $_POST['tprice'][$rowIndex];
echo "<div>Row# {$rowIndex} " . ($stmt->execute() ? 'added' : 'failed') . "</div>";
}
To deny the insertion of a row, use the conditional continue that is commented in my snippet -- of course, write your logic where true is (anywhere before the execute call inside the loop will work).
To adjust submitted values, overwrite the iterated variables (e.g. $vsr, $ofice, etc) before the execute call.
If you'd like to enjoy greater data type specificity, you can replace s (string) with i (integer) or d (double/float) as required.

php push 2d array into mysql

Hay All,
I cant seem to get my head around this dispite the number to examples i read. Basically I have a 2d array and want to insert it into MySQL. The array contains a few strings.
I cant get the following to work...
$value = addslashes(serialize($temp3));//temp3 is my 2d array, do i need to use keys? (i am not at the moment)
$query = "INSERT INTO table sip (id,keyword,data,flags) VALUES(\"$value\")";
mysql_query($query) or die("Failed Query");
Thanks Guys,
Not sure it's be a full answer to your question, but here at least a couple of possible problems :
You should not use addslashes ; instead, use mysql_real_escape_string
It knows about the things that are specific to your database engine.
In your SQL query, you should not use double-quotes (") arround string-values, but single-quotes (')
In your SQL query, you should have as many fields in the values() section as you have in the list of fields :
Here, you have 4 fields : id,keyword,data,flags
but only one value : VALUES(\"$value\")
You should use mysql_error() to know what was the precise error you've gotten while executing the SQL query
This will help you find out the problems in your queries ;-)
<?php
// let's assume we have a 2D array like this:
$temp3 = array(
array(
'some keywords',
'sme data',
'some flags',
),
array(
'some keywords',
'sme data',
'some flags',
),
array(
//...
),
);
// let's generate an appropriate string for insertion query
$aValues = array();
foreach ($temp3 as $aRow) {
$aValues[] = "'" . implode("','", $aRow) . "'";
}
$sValues = "(" . implode("), (", $aValues) . ")";
// Now the $sValues should be something like this
$sValues = "('some keywords','some data', 'someflags'), ('some keywords','some data', 'someflags'), (...)";
// Now let's INSERT it.
$sQuery = "insert into `my_table` (`keywords`, `data`, `flags`) values $sValues";
mysql_query($sQuery);
As an addition to the useful answers already given, if you have a big table that you need to insert it might not fit in one SQL statement. However, making a separate transaction for each row is also slow. In that case, we can tell MySQL to process multiple statements in one transaction, which will speed up the insertion greatly for big tables (>1000 rows).
An example:
<?php
function dologin() {
$db_username = 'root';
$db_password = 'root';
$db_hostname = 'localhost';
$db_database = 'logex_test';
mysql_connect($db_hostname, $db_username, $db_password);
mysql_select_db($db_database);
}
function doquery($query) {
if (!mysql_query($query)) {
echo $query.'<br><br>';
die(mysql_error());
}
}
function docreate() {
doquery("drop table if exists mytable");
doquery("create table mytable(column1 integer, column2 integer, column3 integer)");
}
function main() {
$temp3 = array(
array('1','2','3',),
array('4','5','6',),
array('7','8','9',),
);
dologin();
docreate();
doquery("start transaction");
foreach($temp3 as $row)
doquery("insert into mytable values('" . implode("','", $row) . "')");
doquery("commit") or die(mysql_error());
}
main();
?>
Try this :
// lets array
$data_array = array(
array('id'=>1,'name'=>'a'),
array('id'=>2,'name'=>'b'),
array('id'=>3,'name'=>'c'),
array('id'=>4,'name'=>'d'),
array('id'=>5,'name'=>'e')
)
;
$temp_array = array_map('implode', $data_array, array('","' ,'","','","','","','","'));
echo $query = 'insert into TABLENAME (COL1, COL2) values( ("'.implode('"),("', $temp_array).'") )';
mysql_query($query);

Categories