I'm trying to use an upload page to insert into my database with the following code:
if($file!=="")
{
echo "<br/>".$file;
$handle = fopen($file, "r");
$row = 0;
$delete_records = mysql_query("DELETE FROM affiliationagreements");
$delete_records = mysql_query("DELETE FROM college");
$delete_records = mysql_query("DELETE FROM program");
$delete_records = mysql_query("DELETE FROM facility");
$delete_records = mysql_query("DELETE FROM submitor");
$delete_records = mysql_query("DELETE FROM location");
//will loop each record in the CSV file
while(($fileop = fgetcsv($handle,1000,",")) !== false )
{
//columns names of the CSV file are not needed
if($row==0)
{
$row++;
}
else
{
//accept apostrophes in the strings
$fileop = array_map("mysql_real_escape_string",$fileop);
$sql = mysql_query("INSERT INTO affiliationagreements(id, AANumber, Facility, Submitor, Program, Location, College, SubmissionDate, Action, EffectiveDate, Status, ExpirationDate)
VALUES('',
'$fileop[0]',
'$fileop[1]',
'$fileop[2]',
'$fileop[3]',
'$fileop[4]',
'$fileop[5]',
'$fileop[11]',
'$fileop[23]',
'$fileop[24]',
'$fileop[25]',
'$fileop[26]')
")or die(mysql_error());
To just give a sample, and when I upload my CSV file to add the values, I print them out in the console and see that the values are being read correctly and they are. But, once my php script ends and I return to the main page, my dates are all null. None of them are the values what are reflected in the csv file. Here is the schema for my database:
CREATE TABLE `affiliationagreements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`AANumber` varchar(20) DEFAULT NULL,
`Facility` varchar(150) DEFAULT NULL,
`Submitor` varchar(50) DEFAULT NULL,
`Program` varchar(60) DEFAULT NULL,
`Location` varchar(50) DEFAULT NULL,
`College` varchar(50) DEFAULT NULL,
`SubmissionDate` date DEFAULT NULL,
`Action` varchar(50) DEFAULT NULL,
`EffectiveDate` date DEFAULT NULL,
`Status` varchar(50) DEFAULT NULL,
`ExpirationDate` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
If I change SubmissionDate, EffectiveDate, and ExpirationDate to a varchar, they insert correctly but I can't use varchar because I am comparing date values. And Advice?
***Update. In the CSV file, the format is MM/DD/YYYY. I didn't think this would be a problem. Would it be better to change this? And I'm deleting records because my boss wanted the DB cleared before a file was reuploaded since the uploaded file was an update of the previously uploaded one. ****
Check your date format, as MySql it needs to be in YYYY-MM-DD format
INSERT INTO table SET date = '2014-05-13'
If you have different format, the date will store '0000-00-00' instead. So double check your insertion by echo your query string before running the query.
mysql date field only accepts dates in this format: 0000-00-00
You can use DATE_FORMAT() in your insert query but I can't give exaples becuase you didn't post what format your actual date is.
http://www.w3schools.com/sql/func_date_format.asp
Related
I have this code and for some reason it won't get inserted into my database. It's basically taking an array, turning it into a string and then submit the values.
(If you need me to edit to show my whole code, I will do so)
Code I am having issues with down below
$array = array($RaceNumber,$Track,$Num,$HorseName,$Odds,$Color,$Jockey,$Trainer,$PostTime,$Course,$RaceDistance,$Win,$Place,$Show);
for ($a=0; $a<$Num; $a++) {
$dataArray=array($RaceNumber[$a],$Track[$a],$Num[$a],$HorseName[$a],$Odds[$a],$Color[$a],$Jockey[$a],$Trainer[$a],$PostTime[$a],$Course[$a],$RaceDistance[$a],$Win[$a],$Place[$a],$Show[$a]);
$dataArray--;
for ($j=0; $j<$Num; $j++) {
$RaceNumber=$dataArray[0];
$Track=$dataArray[1];
$Num=$dataArray[2];
$HorseName=$dataArray[3];
$Odds=$dataArray[4];
$Color=$dataArray[5];
$Jockey=$dataArray[6];
$Trainer=$dataArray[7];
$PostTime=$dataArray[8];
$Course=$dataArray[9];
$RaceDistance=$dataArray[10];
$Win=$dataArray[11];
$Place=$dataArray[12];
$Show=$dataArray[13];
$sql="INSERT INTO `$Date` (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('$RaceNumber','$Track','$Num','$HorseName','$Odds','$Color','$Jockey','$Trainer','$PostTime','$Course','$RaceDistance','$Win','$Place','$Show')";
echo $sql;
mysqli_query($query2,$sql);
}
}
when I echo my $sql I get
INSERT INTO 2018-09-20 (RaceNumber,Track,HorseNum,HorseName,Odds,Color,JockeyName,TrainerName,PostTime,Course,RaceDistance,Win,Place,Show) VALUES ('1','FingerLakes','1','','','Red','','','','Dirt','','none','none','none')
But when I do my query, it isn't inserting into database.
Part of my code where I create the datatable
<?php
if(isset($_POST['submit'])) {
$Date = $_POST['date'];
$sql = "CREATE TABLE IF NOT EXISTS `$Date` (
`Id` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`RaceNumber` varchar(255) NOT NULL,
`Track` varchar(255) NOT NULL,
`HorseNum` varchar(255) NOT NULL,
`HorseName` varchar(255) NOT NULL,
`Odds` varchar(255) NOT NULL,
`Color` varchar(255) NOT NULL,
`JockeyName` varchar(255) NOT NULL,
`TrainerName` varchar(255) NOT NULL,
`PostTime` varchar(255) NOT NULL,
`Course` varchar(255) NOT NULL,
`RaceDistance` varchar(255) NOT NULL,
`Win` varchar(255) NOT NULL,
`Place` varchar(255) NOT NULL,
`Show` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8"
;
$query2 = mysqli_connect('localhost','root','','Races');
$z= mysqli_query($query2, $sql) or die("Table already exist.. please try again");
echo "Your Table ".$Date." is successfully created <br/>";
$RaceNum = $_POST['RaceNum'];
$i=1;
I am receiving in my error log of
2018-09-20 16:00:59 9444 [ERROR] Incorrect definition of table mysql.column_stats: expected column 'max_value' at position 4 to have type varbinary(255), found type varchar(255).
You are using a column named Show that's a reserved keyword in mysql, add backquotes to it and the insert query should work.
It's worth noting that you shouldn't name your table with only digits and hyphens.
For reference here is the complete list of the reserved keywords:
https://dev.mysql.com/doc/refman/8.0/en/keywords.html
I am trying to generate invoice id in each invoice, now i am having thousands of invoices, Now while adding from different ip same time i am getting duplicate invoice ids how to prevent it,
invoice id generating by getting the last inserted invoice id and increment 1 to it.
my function as follows parameters
get_new_tbl_id('table_name','invoice_id_column','string to strip (INV in INV0012)','any conditions');
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
return $string.$new_id;
}
My table as follows
CREATE TABLE IF NOT EXISTS `tbl_invoice` (
`invoice_tbl_id` int(11) NOT NULL AUTO_INCREMENT,
`invoice_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`invoice_ip` varchar(25) NOT NULL,
`invoice_status` tinyint(1) NOT NULL DEFAULT '0',
`invoice_added_by` smallint(6) NOT NULL,
`invoice_edited_by` smallint(6) NOT NULL,
`invoice_date` date NOT NULL,
`invoice_id` varchar(15) NOT NULL,
`customer_id` varchar(11) NOT NULL,
`invoice_credit_date` tinyint(4) NOT NULL,
`invoice_credit_status` tinyint(1) NOT NULL DEFAULT '0',
`total_items_count` smallint(6) NOT NULL,
`invoice_total_amount` varchar(20) NOT NULL,
`invoice_grandtotal_amount` double NOT NULL,
`invoice_discount` double NOT NULL DEFAULT '0',
`invoice_total_card_amount` double NOT NULL,
`invoice_total_cash_amount` double NOT NULL,
`invoice_total_profit` varchar(10) NOT NULL,
`cashier_approval` tinyint(1) NOT NULL DEFAULT '0',
`cashier_approval_id` smallint(6) NOT NULL,
`cashier_approval_time` datetime NOT NULL,
`cashier_approval_ip` varchar(20) NOT NULL,
`invoice_delete_note` text NOT NULL,
PRIMARY KEY (`invoice_tbl_id`),
KEY `invoice_id` (`invoice_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
Use a myisam table to generate the ids for you with 2 fields. The 1st field contains the prefix (this is $string in your function), the second should be an auto increment field. Add a primary key on these 2 fields, but the prefix field must be the 1st one in the index. If you insert a new row into this table with a prefix, then mysql will increment the auto increment value within that group.
See myisam notes section in mysql documentation on auto increment for details and example.
CREATE TABLE animals (
grp ENUM('fish','mammal','bird') NOT NULL,
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (grp,id)
) ENGINE=MyISAM;
INSERT INTO animals (grp,name) VALUES
('mammal','dog'),('mammal','cat'),
('bird','penguin'),('fish','lax'),('mammal','whale'),
('bird','ostrich');
If your base table is mysql, then just alter it to get this behaviour, if not, then create a separate myisam table, do the inserts into that one first, then obtain the ids fo use in your main table.
May there will be some optimized solution, but for now I can give you this solution
use static variable lock if one person is getting id make $lock=true and keep other requests on waiting for 1 second and check again by goto start; until first request is completed; make $lock=false; at the end to release the function.
public static $lock=false;
function get_new_tbl_id($tbl_name,$id_field,$string,$options='')
{
global $lock;
start:
if($lock==true){
sleep(1);
goto start;
}
if($lock==false){
$lock==true;
}
$new_id = 0;
$query_count_rows = "SELECT MAX(CONVERT(replace(replace($id_field,',',''),'$string',''), SIGNED INTEGER)) as $id_field FROM $tbl_name WHERE $id_field LIKE '$string%' $options";
$count_rows = mysql_query($query_count_rows);
$num_rows = mysql_num_rows($count_rows);
if($num_rows >0)
{
$last_row = mysql_fetch_assoc($count_rows);
$last_id = $last_row[$id_field];
$last_inserted_id = intval(str_replace($string,'',$last_id));
$new_id = $last_inserted_id+1;
}
else
$new_id = 1;
$format = '%1$03d';
$new_id=sprintf($format,$new_id,'');
$lock=false;
return $string.$new_id;
}
I have strange problem that I am unable to figure out, any help would be appreciated!.
The problem is I am trying to store an object into mysql database, when I execute the insertion command I run successfully, but when I check the table, all columns have the new inserted data expect the column with Blob datatype.
here is the table
CREATE TABLE `uc_opportunities` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`org_id` int(11) DEFAULT NULL,
`dateTime` int(11) NOT NULL,
`subject` varchar(200) NOT NULL,
`text` varchar(2000) DEFAULT NULL,
`zipcode` varchar(10) NOT NULL,
`location` varchar(100) DEFAULT NULL,
`schedule` blob NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=48 DEFAULT CHARSET=utf8;
and here is the insertion function:
public function addOpportunity($org_id)
{
global $mysqli,$emailActivation,$websiteUrl,$db_table_prefix; //
echo "inside add opportunity<br>";
var_dump($this->schedule);
$stmt = $mysqli->prepare("INSERT INTO ".$db_table_prefix."opportunities (
org_id,
dateTime,
subject,
text,
zipcode,
schedule
)
VALUES (
?,
?,
?,
?,
?,
?
)");
$schedule_serialized = serialize($this->schedule);
$stmt->bind_param("iissib", $org_id, $this->dateTime, $this->subject,$this->postText, $this->zipcode, $schedule_serialized );
$result = $stmt->execute();
echo "execution result ".$result."<br>";
$inserted_id = $mysqli->insert_id;
$stmt->close();
$this->post_id = $inserted_id;
}
All columns except schedule are inserted, I check if the insertion function receive the schedule correctly using var_dump($this->schedule) and it is correct. What do you think might be the problem?
Thank you
Please check out the mysqli documentation in reference to saving blob data and mysql config for max_allowed_packet. It's possible this could be your issue since I don't know how big your serialized data is:
php.net mysqli
first of all,change your data if it is image,audio,document etc into binary and schedule column to longBlob then run your insert command.Some times due to larger binary data insert doesn`t work.So give a try
I have mysql table as follows;
CREATE TABLE IF NOT EXISTS `cheque_data` (
`auto_no` int(11) NOT NULL AUTO_INCREMENT,
`job_no` int(11) NOT NULL,
`client_id` text NOT NULL,
`ch_no` text NOT NULL,
`ch_date` date NOT NULL,
`ch_bank` text NOT NULL,
`ch_amount` decimal(10,2) NOT NULL,
`sync` int(1) NOT NULL DEFAULT '0',
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`auto_no`)
)
When I run SQL command in PHPMYADMIN it will retrieve row;
SELECT * FROM `cheque_data` WHERE timestamp='2014-03-10 19:37:31'.
But in PHP,
$sql = "select * from `cheque_data` where timestamp = '2014-03-10 19:37:31'";
$result_remote = mysqli_query($con,$sql) or die(mysqli_error($con));
$row_count = mysqli_num_rows($result_remote);
echo $row_count; //no data
It doesn't give any data. But when I change timestamp to other column, it works.
$sql = "select * from `cheque_data` where auto_no = '1'";
$result_remote = mysqli_query($con,$sql) or die(mysqli_error($con));
$row_count = mysqli_num_rows($result_remote);
echo $row_count; //data found
I want to know, what is the reason for this issue?
It is only not working with where timestamp
Thank you,
Sameera
add backticks(`) around timestamp field, as it is reserved word or use this query
$sql = "select * from `cheque_data` where `timestamp` = '2014-03-10 19:37:31'";
Possibly, the problem in your PHP script, not MySQL.
P.S. keep in mind, that it is better to wrap column names in ` not to confuse MySQL. In your statement it is okay, but fyi there is a function called TIMESTAMP(), and in some cases MySQL may think of a non-wraped column name as of a function name.
I'm integrating an RSS feed unto my website and i need to create a table:
CREATE TABLE `stories` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`description` text NOT NULL,
`when` datetime NOT NULL default '0000-00-00 00:00:00',
PRIMARY KEY (`id`)
)
i know how to insert id, title, description but i do not know how to insert the time of the post (user submits them). I used the script given here.
mysql_query("insert into stories (title,description) VALUES ('$_POST[title]','$_POST[description]') ");
For when use the date function:
date('Y-m-d h:i:s')
By default the date function uses the current date/time if you don't supply one as the second argument.