insert an array into mysql database - php

I have the following array which I would like to insert into mysql database.
Item[0] = Soccer
Item[1] = Rugby
Item[2] = Football
Item[3] = Netball
Item[4] = Hockey
I am using the following function to insert into the database, located in functions.php:
//Capture items
function item($register_data)
{
array_walk($register_data,'array_clean');
$fields = ' '.implode(',',array_keys($register_data)).' ';
$data = '\''.implode('\',\'',$register_data).'\'';
//Insert user Data into the database
$query = "INSERT INTO items ($fields) VALUES ($data)";
mysql_query($query);
}
Now this is how I insert:
for($i =0;$i<4;$i++)
{
$item = array($i = item[i]);
}
//Call the function to insert into the database
item($item);
This method doesn't seem to work. Please assist

PHP has a built in serialize & deserialize functions (http://php.net/manual/en/function.serialize.php) for that. You can pass any object or array to it, and it will return a serialized string, which you can store in a single field in the database.

Since your items table has two columns, one of which is id (auto increment) you're going to want to skip over it and only specify the second column ItemName. This is described in the mysql documentation on this page.
Lets say you want to insert 5 sports in this table:
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
You'll want the query to look something along these lines:
INSERT INTO items (ItemName) VALUES ('Soccer'), ('Rugby'), ('Football'), ('Netball'), ('Hockey');
The code would look something like this:
function insert($insert_data)
{
$fields = implode(', ', $insert_data);
$data = '(\''.implode('\'), (\'', $insert_data).'\')';
//mysql_query("INSERT INTO items (ItemName) VALUES $data;");
echo "INSERT INTO items (ItemName) VALUES $data;";
}
$sports = array();
$sports[0] = "Soccer";
$sports[1] = "Rugby";
$sports[2] = "Football";
$sports[3] = "Netball";
$sports[4] = "Hockey";
insert($sports);
You may also want to sanitize the strings first and take a look at mysqli since mysql is pretty outdated.

Related

Can i use Multiple Array in a foreach loop?

I have researched several related question in this forum and google, Kindly assist . I am trying to insert some values into database from several arrays stored in session. I also have some single values stored in some session also which i want to insert into multiple rows of dbase table.
//First, I recall the values stored in sessions from previous pages into the current page as below.
//take note of the comment in front of the sessions and All array contains the same number of values except for the first two sessions.
$ticketid="t".date('dmyHis').mt_rand (1000,9999);
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;//Not array, contains single value
$_SESSION['ticketid']=$ticketid;//Not array, Contains single value
$_SESSION['gamecode'];//array
$_SESSION['starttime'];//array
$_SESSION['optioncode']//array
$_SESSION['home'];//array
$_SESSION['away'];//array
$_SESSION['odd'];//array
Here, I connected to dbase. //Works fine.
require('gumodb.php');
Here i try to start a loop using one array session as key
foreach($_SESSION['starttime'] as $ro => $col){
mysql_query("INSERT INTO reg_bet (bettime, ticketid,matchcode,starttime,home,away,optionodd,optioncode) VALUES('$_SESSION[bettime]','$_SESSION[ticketid]','$_SESSION[gamecode]', '$_SESSION[starttime]','$_SESSION[home]','$_SESSION[away]','$_SESSION[odd]','$_SESSION[optioncode]' ) ")
or die(mysql_error());
}
It returns Notice: Array to string conversion in C:\xampp\htdocs\gumo\consel.php on line 61
EDIT QUESTION
I am trying to achieve something like this.
foreach($_SESSION['gamecode'] as $gc => $gcvalue && $_SESSION['starttime'] as $st =>$stvalue && $_SESSION['optioncode'] as $oc => $ocvalue ){
mysql_query("INSERT INTO reg_bet (matchcode,starttime,optioncode) VALUES('$gcvalue','$stvalue','$ocvalue') ")
or die(mysql_error()); }
$x = json_encode($_SESSION);
$query = "INSERT INTO ".$TABLE_NAME data "VALUES ("$x");";
$mysqli->query( $query );
Encode the session array into a single string and insert in to the table on a row of data.
When you fetch the same data use json_decode to convert the string into array.
Assuming the arrays in the $_SESSION variable are numeric, you could try something like this:
for ($i = 0; $i < $max_index_count; $i++) {
$query = "INSERT INTO ".$TABLE_NAME;
$query += "VALUES (".$_SESSION['index'][$i].");";
$mysqli->query( $query );
}
The above is pseudo code, but the problem is you are trying to use an array as a string. The $_SESSION variable is a multidemsional array, therefore, specify two ibdexes.
After so many trials, i was able to get it done with this
$ticketid="t".date('dmyHis').mt_rand (1000,9999);//ticket id generateed
$bettime= date('d/m/y H:i');
$_SESSION['bettime']=$bettime;
$_SESSION['ticketid']=$ticketid;
$_SESSION['gamecode'];
$_SESSION['starttime'];
$_SESSION['optioncode'];
$_SESSION['home'];
$_SESSION['away'];
$_SESSION['odd'];
require('gumodb.php');
foreach ($_SESSION['gamecode'] as $index => $value)
{
$ge = $_SESSION['gamecode'][$index];
$se = $_SESSION['starttime'][$index];
$oe = $_SESSION['optioncode'][$index];
$he = $_SESSION['home'][$index];
$ay = $_SESSION['away'][$index];
$od = $_SESSION['odd'][$index];
This post the arrays and non array into table row and display
mysql_query("INSERT INTO reg_bet (matchcode,ticketid,bettime,starttime,home,away,optionodd,optioncode) VALUES('$ge','$ticketid','$bettime','$se','$he' ,'$ay','$od' ,'$oe' ) ")
or die(mysql_error());
echo $_SESSION['gamecode'][$index] .'-'. $_SESSION['starttime'][$index].'- '. $_SESSION['optioncode'][$index].' -'. $_SESSION['home'][$index].'- '. $_SESSION['away'][$index].'- '. $_SESSION['odd'][$index].$bettime.' -' .$ticketid.'</br>' ;
}
Thanks for your contributions.

How to insert data in table from RETS search query?

I am trying to insert data in a table. I am using a search query and then FetchRow in while condition to fetch the data in row and want to insert this row in a table directly. I have given the structure of table in this link.
The code for insert values in table in while condition is here:
require_once (ABSPATH . 'wp-admin/includes/upgrade.php');
$query = "(922=MIAMI), (131=2014-12-16+)";
$search = $rets->SearchQuery("Property", $class, $query, array("SystemName" => 1, 'Limit' => 1 ));
if ($rets->NumRows($search) > 0)
{
$fields_order = $rets->SearchGetFields($search);
$this_record = array();
while ($record = $rets->FetchRow($search))
{
foreach ($fields_order as $fo)
{
echo $this_record[] = $record[$fo];
}
$comma_fields_order = implode(",", $fields_order);
$comma_record = implode(",", $this_record );
echo $dfsdf = "INSERT INTO rets_property_2 (".$comma_fields_order.") VALUES (" .$comma_record.")";
dbDelta($dfsdf);
}
}
If I echo the insert query this is :
INSERT INTO rets_property_2 (sysid,1,10,11,13,14,17,19,21,22,25,28,29,30,31,39,45,47,53,54,56,57,59,61,62,63,66,69,71,73,74,75,76,80,92,93,97,98,99,100,102,106,109,110,111,113,114,115,125,126,127,128,129,131,134,136,137,143,144,149,150,157,158,160,161,164,165,167,178,180,181,188,190,193,194,195,206,207,214,223,225,226,227,229,230,232,242,245,246,247,248,250,252,261,263,264,266,267,268,274,275,283,294,295,296,314,315,319,320,321,322,324,326,327,328,329,330,331,332,333,334,335,336,337,338,341,342,347,348,351,352,353,354,355,356,360,361,362,363,364,366,367,368,369,370,372,373,374,375,376,881,886,891,893,894,922,924,1088,1218,1223,1329,1333,1335,1337,1339,1358,1410,1462,1463,1464,1465,1473,1485,1486,1487,1488,1490) VALUES (305578689,Condo/Co-Op/Villa/Townhouse,33131,,,,3003,42,None,,4,,,,Entry Level,Miami Board of Realtors,0,,Cbs Construction,,,Electric Cooling,,Miami-Dade County,,,,ASIA CONDOMINIUM,,,,,,2008-06-12T14:19:47,5,2630,,,,,2,,1,Electric Heat,Condo,9,Yes,ASIA IS BRICKELL KEY ISLAND'S PREMIER LUXURY BLDG. W/ ONLY 123 UNITS, PRIVATE ELEVATORS, SPECTACULAR VIEWS AND MUCH MORE.,,,,,3813,2014-12-23T09:16:55,EWM 09,0648464,6000000,,Daysi Morey,,1,M1242705,,No,,Vacant,EWM Realty International,305-329-7600,,Maximum 20 Lbs,Yes,,0043,,Funding,Yes,5000000,T,EXOTIC LUXURY AND STRIKING DESIGN MAKES ASIA THE # 1 RESIDENCE FOR THE MOST DISCRIMINATING OWNER. SMART TECHNOLOGY, PRIVATE ELEVATORS, FLOOR TO CEILING WINDOWS, BREATHTAKING VIEWS OF BISCAYNE BAY, BAYSIDE, MIAMI RIVER AND MIAMI;S EXHUBERTANT SKYLINE. 12' CIELINGS,MARBLE BATHROOMS, GOURMET CHEF STYLE KITCHEN, LUXE BATH WITH FRENCH VANILLA IMPORTED MARBLE AND MUCH MORE MAKES THIS REMARKABLE RESIDENCE A SANCTUARY NESTLED IN BISCAYNE BAY. ALLOW 24 HOURS NOTICE FOR SHOWINGS.,,,6,6,,,0,,2014-01-24T10:02:22,Active-Available,BRICKELL KEY BLVD.,900,,,4663,Tax Reflects City & County Tax,New Construction,,,42,,0,2007,,None,Yes,Bay Front,2008,Under Construction,Bike/Jog Path,Elevator,0,No Approvals,,,ASIA CONDOMINIUM,,No,,,,Dishwasher,Dryer,Microwave,Electric Range,Refrigerator,Other Equipment/Appliances,Open Balcony,,30,Wood Floors,,Condominium,Elevator,Foyer Entry,Other Interior Features,0,All Amenities,Building Exterior,Cable Tv,1920,365,,,1,1 Assigned Space,2 Or More Spaces,,,0,Other Restrictions,,Elevator Secure,Garage Secured,Lobby Secured,,Condo 5+ Stories,34,Other,Condo,Corner Unit,High Rise,123,,Bay,,900 BRICKELL KEY BLVD. # 3003,,,,0,Miami,Florida,,,http://instatour.propertypanorama.com/instaview/mia/M1242705,2009-02-19T16:00:26,,,,ASIA CONDO UNIT 3003,1573.564,No HOPA,,,2389,No,No,No,No,900 BRICKELL KEY BLVD. 3003,Yes,)
But nothing is being inserted in the table. Where I am wrong? Is there any other method to insert the whole row directly given by fetchrow into the table?
Please show me right direction. I think the problem is with the data type, number and varchar. Then how can I format the insert query where data is coming from the array?
I know my insert query is wrong.
If I do try this
INSERT INTO `rets_property_2` ( `sysid` , `1` )
VALUES ( 526252, 'dsfsdfsdf' )
this will work fine. But the question is How can I get the values from array if the value is string then 'somestringvalue' and if the value is integer then only integervalue and then wrapping them in a array?
$query = "(922=MIAMI), (131=2014-12-16+)";
$search = $rets->SearchQuery("Property", $class, $query, array("SystemName" => 1, 'Limit' => 5 ));
if ($rets->NumRows($search) > 0) {
$fields_order = $rets->SearchGetFields($search);
while ($record = $rets->FetchRow($search)) {
//var_dump($fields_order);
foreach ($fields_order as $fo) {
if( is_numeric($record[$fo])){
$valuesd[] = $record[$fo];
}else{
$onlyconsonants = str_replace("'", "", $record[$fo]);
$valuesd[] = "'".$onlyconsonants."'";
}
}
$comma_fields_order = "`".implode("`,`", $fields_order)."`";
$valuestring = implode(",", $valuesd );
$wpdb->query("INSERT INTO rets_property_2 (".$comma_fields_order.") VALUES (".$valuestring.")");
unset($valuesd);
$valuesd = array();
} /* end while */
} /* end if of number of row */
I would suggest using DBName column names instead of SystemName for your database table column names.
I would also suggest using PDO to prepare/execute your statements.
The below example should help you along:
<?php
$sysid = '1234'
$property_1 = '1111 main'
$stmt = $db->prepare("INSERT INTO table_name(`sysid`, `property_1`) VALUES( ?, ?)");
$stmt->execute(array($sysid, $property_1));

Passing multiple checkbox values to different columns of database

I am pretty new to PHP, but have tried searching for other questions similar to mine and been unable to find anything that is close enough to my situation to help me solve this.
I am trying to code a web page that allows users to select as many or as few items as they would like to order. The item values are identical to their Primary Key in the Item table.
Once submitted, each different item value should be input into the same row of a database table based on the date{pk}. Within that row, there are numerous columns: Item1ID, Item2ID, Item3ID, etc.
So far, the value of each item selected is assigned to a new array. However, I cannot simply input the array values into a column -- I need each array index to be placed into a sequential column. The code is below:
$date = new DateTime();
$td = $date->format('Y-m-d');
$x = 1;
$checkedItems = $_POST['Item'];
$count = count($checkedItems);
echo $count;
$foodID = "Item".$x."ID";
While($x<=$count){
if(isset($_POST['Item'])){
if (is_array($_POST['Item'])) {
foreach($_POST['Item'] as $values){
$selectedFoods = substr($values,0,4);
$addFoodOrderQuery= sprintf("UPDATE WeeklyBasketFoodOrder SET '%s' = %s WHERE `foodOrderDate` = '%s'",
$foodID, $selectedFoods, $td);
$result= mysqli_query($db, $addFoodOrderQuery);
}
}
} else {
$values = $_POST['Item'];
echo "You have not selected any items to order.";
}
$x++;
}
If you need any further clarification, please let me know. After submitting the code, the database item#ID tables are different, but they are now empty instead of "NULL."

Separate merged SQL rows with a comma

I'm having a bit of trouble getting my retrieved values from an SQL query into the correct format.
I've managed to join multiple rows into the one value, however I am not sure how to make it separate each of the values with a comma. Essentially I need all the ID's of a product to be retrieved as, for example, if the database had values of '5,6,9,1' '1,3,4' and '2,1' I want it to throw a comma in between each like -> '5,6,9,1,1,3,4,2,1' instead is doing something more like -> '5,6,911,3,42,1' which is what it is doing at the moment.
The code I'm using is below. Any help would be greatly appreciated.
$hist = "SELECT ORDITEMS FROM cust_orderc WHERE ORDDATE >
to_date('".$olddate."','dd/mm/yyyy')";
$histitem = OCIParse($db, $hist);
OCIExecute($histitem);
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'];
}
echo "$pastitem";
You can do same in oracle using LISTAGG
$hist = "SELECT LISTAGG(ORDITEMS) as ORDITEMS FROM cust_orderc WHERE ORDDATE > to_date('".$olddate."','dd/mm/yyyy')";
Edit OR PHP way
$pastitem = '';
while($row = oci_fetch_array($histitem)){
$pastitem .= $row['ORDITEMS'] . ',';
}
$pastitem = trim($pastitem, ",");
echo $pastitem;

Multiple records inserting into MySql from PHP form

I think I've got a tiny mistake in my code so when I try to add two records to MySQL database it adds them both, but at the moment its only adding the second row that should be inputted. SO for example I have two RefTitle fields, two RefSurname fields and so on!
Some PHP Code:
<?php
if(empty($err)) {
for($i = 0; $i < 2; $i++)
{
$RefTitle = $_POST['RefTitle'][$i];
$RefSurname = $_POST['RefSurname'][$i];
$RefForenames = $_POST['RefForenames'][$i];
$RefInstitute = $_POST['RefInstitute'][$i];
$RefEmail = $_POST['RefEmail'][$i];
$RefTelephone = $_POST['RefTelephone'][$i];
$EmailOK = $_POST['EmailOK'][$i];
$sql_insert = "INSERT into `referees`
(`RefTitle`,`RefSurname`,`RefForenames`,`RefInstitute`, `RefEmail`,
`RefTelephone`,`EmailOK`)
VALUES
('$RefTitle','$RefSurname','$RefForenames','$RefInstitute','$RefEmail',
'$RefTelephone','$EmailOK'
)
"; ?>
I have the [] after each name field in my html form.
Thanks
Here's what I think is happening.
In the loop, you're adding the current query to a string, overwriting the previous query. After the loop ends, you run mysql_query but this will only run on the last query generated by the loop.
You have two ways to fix this:
Execute the query within the loop on every iteration. Pseudo code:
for ($i = 1 to 100)
{
$query = //build your query;
mysql_query($query);
}
Alternatively, (and the better way) is to use a value list in your insert statement.
An insert with a list of values looks like this
INSERT INTO table VALUES (1,2,3), (4,5,6), (7,8,9)
So, (pseudo code again)
$query = "INSERT INTO table VALUES ";
for ($i = 1 to 100)
{
$query .= " (";
$query .= "" //comma seperate the values of the current iteration
$query .= "),";
}
//after loop ends, remove the trailing extraneous comma
// execute the entire query at once
mysql_query($query);

Categories