I am trying to implode some variables and insert them into a MySql database, but for some reason it is not working. I have been trying for hours and I''m just not sure what I'm doing wrong.
If you can help it would be much appreciated.
$AddressString = "address1,address2,address3,address5,postcode";
$AddressSplit = explode( ",", $AddressString ); //split the address string
$StringLength = count( $AddressSplit ) - 1;
$s = 0; //trim any white spaces from the address string
while ( $s < count( $AddressSplit ) ) {
$AddressSplit[$s] = trim( $AddressSplit[$s] );
$s++;
}
//Create the Values to insert into DB
$MysqlValues = implode( "','", $AddressSplit );
$MysqlValues = "'$MysqlValues'";
$NumberVals = count( $AddressSplit );
$t = 1;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
$TableNames = implode( ", ", $ad );
mysql_query( "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')" );
}
Because you start making the field names 1 based, your are one field short!
In the end you must end with a equal number of fields and values.
Try this:
$t = 0;
while ( $t < $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Or, if you do not want the first field to be "add", change it like this:
$t = 1;
while ( $t <= $NumberVals ) {
$ad[$i] = "add$i";
$t++;
}
Of course, it would have been a easy test to do:
$sql = "INSERT INTO pstc_add_main (" . $TableNames . ",add10,date)
VALUES (" . $MysqlValues . ",'$cdate')";
var_dump($sql);
mysql_query($sql);
Not tested,
I doubt you change,
$MysqlValues = implode("','", $AddressSplit);
to
$MysqlValues = implode(",", $AddressSplit);
Just use
$MysqlValues = implode( ",", $AddressSplit );
and try to edit the code like
mysql_query( "INSERT INTO pstc_add_main (".$TableNames." ,add10,date)
VALUES (" . $MysqlValues . ",$cdate)" );
Related
how to add comma in query for next item? Add more details to the question.
// Indented the codes to make it more readable
$participants = [602, 600];
$query = array();
$query[] = 'INSERT INTO ' .
$db->nameQuote( '#__social_conversations_participants' );
$query[] = '(' . $db->nameQuote( 'conversation_id' ) .',' .
$db->nameQuote( 'user_id' ) . ',' . $db->nameQuote( 'state' ) . ')';
$query[] = 'VALUES';
foreach( $participants as $userId ){
$query[] = '(' . $db->Quote( $conversationId ) . ',' .
$db->Quote( $userId ) . ',' . $db->Quote( 1 ) . ')';
//this is not working because next() in this case always return
false
// Indented the codes to make it more readable
if( next( $participants ) !== false ){
$query[] = ',';
}
}
// Glue query back.
$query = implode( ' ' , $query );
var_dump($query);exit;
Found solution from here: PHP: Insert separated comma string value with as multiple array value Into MySql
<?php
$myString = "Red,Blue,Black";// incoming string comma names
$myArray = explode(',', $myString);
print_r($myArray);
$sql = "INSERT INTO `cat_interest`(`id`,`categories`) VALUES";
foreach($myArray as $value){
$sql .= " (1, '{$value}'),";
}
echo rtrim($sql, ',');
I am using PHP to create an XML document from a database to import into Adobe InDesign. I want to be able to add a comma after each entry but not on the last one. I have tried using implode() but I have had no luck. Any help would be greatly appreciated. Here is the code with out any attempt at adding the comma. I can just add a comma after the closing but that will still give me one on the last entry. Any advice on how to attack this would be much appreciated. Thanks!
function getAssocXML ($company) {
$retVal = "";
// Connect to the database by creating a new mysqli object
require_once "DBconnect.php";
$staffResult = $mysql->query("
SELECT company,
fName,
lName,
title,
contact1,
contact2
FROM staff
WHERE company = '$company'
AND title
LIKE '%Associate%'
AND archive = 0
");
if ($staffResult->num_rows >= 1 && $staffResult->num_rows < 4) {
$retVal = $retVal;
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . " — Associate
";
$staffResult->free();
}
if ($staffResult->num_rows > 4) {
$retVal = $retVal;
$retVal = $retVal . "<staffHeader>Associates: </staffHeader>";
for ($i = 0; $i < $staffResult->num_rows; $i++) {
// Move to row number $i in the result set.
$staffResult->data_seek($i);
// Get all the columns for the current row as an associative array -- we named it $aRow
$staffRow = $staffResult->fetch_assoc();
// Write a table row to the output containing information from the current database row.
$retVal = $retVal . "<staff>";
$retVal = $retVal . "<name>" . $staffRow['fName'] . " " . $staffRow['lName'] . "</name>";
$retVal = $retVal . "<contact>" . staffContact($staffRow['contact1'], $staffRow['contact2']) . "</contact>";
$retVal = $retVal . "</staff>";
}
$retVal = $retVal . "
";
$staffResult->free();
}
return $retVal;
}
print getAssocXML(addslashes($aRow['company']));
You can do it with the help of this query
echo join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1)), 'strlen'));
OR
$last = array_slice($array, -1);
$first = implode(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last), 'strlen');
echo implode(' and ', $both);
I'm afraid that I don't readily grasp your intent here. I don't see anything in your code that is using any sort of array, which is a pre-requisite for implode() (a.k.a. join())
However, here's a little trick that I've used numerous times when I am building something in a loop:
$result = "";
$comma = "";
foreach (...) {
.. calculate some $value ..
$result = $result . $comma . $value;
$comma = ",";
}
The first time through the loop, $comma isn't a comma! It's an empty string. At the end of the first iteration through the loop, it becomes a comma, for use next time. It's a simple but effective way to build an arbitrarily-long "comma-separated string" in-place.
HTH!
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
}
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
Got error
Fatal error: [] operator not supported for strings
Tweaked code from add function which worked. Wanted to have fields and values updated dynamically without using variables, i.e. $_POST['address'].
$query .= $fields . "=" . $values . ", ";
seem not to be working. Not sure what cause the error: Fatal error: [] operator not supported for strings. How to insert field = value in sql query?
Use like this
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$query .= $key . "='" . $data[$key] . "' ,";
}
}
$query = substr($query,0,strlen($query)-1);
$query = $query . " WHERE id = '".$id."' ";
Look at the foreach loop!!!
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
$fields = implode(" ", $fields); // Mistake done here
$values = implode(" ", $values); // Mistake done here
$query .= $fields . "=" . $values . ",";
}
Change your those two line and the next line outside the loop. May be this solve your problem.
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . $this->db->real_escape_string($data[$key]) . "'";
}
}
$fields = implode(" ", $fields);
$values = implode(" ", $values);
$query .= $fields . "=" . $values . ",";
Follow my code. Where no need implementation implode() function. I have changed your function code. try it.
public function update($id, $table, $data, $exclude = array()){
$query = "UPDATE $table SET";
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$queryArr[] = $key . "='" . $this->db->real_escape_string($data[$key]);
}
}
$query = implode(" ,", $queryArr);
$query = $query . "WHERE id = '".$id."' ";
if(!$this->db->query($query)){
echo "Something wrong with query ";
}
else{
echo "successfully updated";
}
}
i would like to import a txt-file with datas for a project. The file have different sections.
$file = fopen( $filename, "r" );
$object = array();
while( !feof( $file ) )
{
$line = fgets($file);
$items = explode( ";", $line );
//Import the global values
if( count($items) == 1 )
{
$arraySection = str_replace("#", "",trim($items[0]) );
}
else if ( count($items) == 3 )
{
$object[$arraySection][$items[0]] = $items[1];
}
else if ( count($items) == 4 )
{
//$object[$arraySection][] = array("gewerknummer" => $items[1], "gewerkbezeichnung" => $items[2]);
}
//Import the articel
else if ( count($items) > 4 )
{
if( $items[0] == "Artikel-Nr" )
{
$articelrow = $items;
}
else
{
$articeldetails = array();
for($i = 0; $i < count($items)-1; $i++)
{
$articeldetails[] = array($articelrow[$i]=>$items[$i]);
}
$object["artikel"] = array(
$articeldetails
);
}
}
}
//Start of import the array to the database
$arrValue = array();
for($i = 0; $i < count($object['artikel']); $i++)
{
$tArray = array();
$tArray[] = $object['Objekt']['Objektnr'];
$tArray[] = $object['SuAdresse']['SUNr'];
$tArray[] = $object['artikel'][$i][0]['Artikel-Nr'];
$tArray[] = "'" . $object['artikel'][$i][1]['Artikel']. "'";
$tArray[] = "'" . $object['artikel'][$i][2]['Beschreibung'] . "'";
$tArray[] = "'" . $object['artikel'][$i][3]['Einheit'] . "'";
$tArray[] = "'" . str_replace(",", ".", $object['artikel'][$i][4]['Preis-Pro-Einheit']) . "'";
$tArray[] = $object['artikel'][$i][5]['AnzahlParameter'];
$tArray[] = "'" . $object['artikel'][$i][6]['P1_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][7]['P2_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][8]['P3_Einheit'] . "'";
$tArray[] = "'" . $object['artikel'][$i][9]['MBS Artikel'] . "'";
$tArray[] = $object['artikel'][$i][10]['Status'];
$tArray[] = $object['artikel'][$i][11]['SuArtikel'];
$tArray[] = $object['artikel'][$i][12]['SuGewerke'];
$tArray[] = "'" . $object['artikel'][$i][13]['PreisStatus'] . "'";
if ( empty( $object['artikel'][$i][14]['ZulageMindermengenArtikelNr'] ) )
$tArray[] = 0;
else
$tArray[] = 0 . $object['artikel'][$i][14]['ZulageMindermengenArtikelNr'];
$arrValue[] = "(" . implode(",", $tArray) . ")";
}
$query = "INSERT INTO objekt_artikel
(
id_objekt,
id_subunternehmer,
artikelnummer,
artikel,
beschreibung,
einheit,
preis_pro_einheit,
anzahl_parameter,
p1_einheit,
p2_einheit,
p3_einheit,
mbs_artikel,
status,
su_artikel,
su_gewerk,
preis_status,
zulage_mindermengen_artikel_nummer
)
VALUES " . implode(",", $arrValue);
But the articels are not added right to the multi-array, because the loop for the query creates only one insert, but when i make a var_dump of of the $object, there looks that the values all be inserted to the array.
I think i have a logic error with filling the array and reading it out.
echo count($object['artikel']) . "\n";die();
This give me the result, that only one Element in the array, but normaly it have to be over 800.
The Element in the array is the last one from the hole Articel list.
Change:
$object["artikel"] = array(
$articeldetails
);
to:
$object["artikel"][] = $articeldetails;
You're not adding to $object['artikel'] each time, you're overwriting it.
You are replacing the same variable each time you go in the while loop...
$object['artikel'] = array($articeldetails);
With this affectation, the array $object has the same cell ('artikel') replaced everytime...
Here is my situation.
I am sending records to database through php file. Then I have a date field being set with now(). It adds the date in this format: 2013-08-01
Then I am exporting the database to a csv. It all works fine. However, I need to take the dashes out when I am exporting it to the csv. So I need it to read: 20130801
Is there a way to do this? Here is my export to csv code:
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$filename = "APGE_ELEC_" . $to;
header('Content-Disposition: attachment; filename="'.$filename.'".csv"');
$hostname = ""; //SET SERVER/HOSTNAME
$dbusername = ""; //SET DATABASE USERNAME
$dbname = ""; //SET DATABASE NAME
$dbpassword = ""; //SET DATABASE USERNAME
$dbhandle = mysql_connect($hostname, $dbusername, $dbpassword)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($dbname,$dbhandle)
or die("Could not select Data Base");
//$query = "SELECT * FROM v88374 WHERE ((date >= '$from') AND (date <= '$to'))";
$query = "SELECT * FROM v88374 WHERE date >= DATE_FORMAT('" . $from . "', '%Y%m%d') AND date <= DATE_FORMAT('" . $to . "', '%Y%m%d')";
//$query = "SELECT * FROM v88374 WHERE date >= DATE_FORMAT($from) AND date <= DATE_FORMAT($to)";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) ."|" . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = $value . '|' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
print "$header\n$data";
exit();
The $to and $from are parameters for searching for date range in the database. So we can leave that alone.
You need to select the formatted time
$query = "SELECT *, DATE_FORMAT(date,"%Y%m%d") FROM v88374 WHERE date >= DATE_FORMAT('" . $from . "', '%Y%m%d') AND date <= DATE_FORMAT('" . $to . "', '%Y%m%d')";
SELECT DATE_FORMAT(datefield, '%Y%m%d')
if you want to do it directly in the database.
This problem can be easily tackled by taking advantage of the way MySQL processes the value in the Date field. Just add 0 and the dashes will be removed
select now();
//gives 2019-12-03 08:44:10
select now()+0;
//gives 20191203084504
You can process this integer as a string and get whatever parts of this are needed.
You could use str_replace() like you did for the quotes, but modify it for dashes, replacing them with empty strings.
$value = str_replace( '-' , '' , $value );
This poses some danger, though. What if you have other data types that use dashes? They'd be corrupted. Another option is to use explode() and checkdate() to make sure it's a date before you remove the dashes. Example:
$dt = explode("-", $value); // Yields array([0] => 2013, [1] => 08, [2] => 01)
// checkdate(int month, int day, int year)
if (checkdate($dt[1], $dt[2], $dt[0])) {
// It's a date.
$value = str_replace('-','',$value);
}
$newDate = str_replace('-', '', $oldDate)
Is that what you're looking for?
In addition php provides some awesome date formatting features: http://php.net/manual/en/function.date.php
$date="2013-08-01";
$converted_date=date("Ymd", strtotime($date));
I tend to prefer a more OOP approach. This way if you ever need to change the format, you can easily modify it.
$date = new DateTime($date_from_mysql);
echo $date->format('Ymd'); // Or adjust the format how you like
Of course, you shouldn't be using the deprecated ext/mysql extension for new projects anyway.