CONTROLLER
$date=date("Y-d-m");
$succes=$this->pl->insert_ad($brandID,$model,$price,$year,$picture,$resized,$fuels,$id_usera,$date);
Model
public function insert_ad($brand,$model,$price,$year,$picture,$resized,$fuels,$date)
{
$sql1="INSERT INTO `ads`(`model`, `year`, `price`, `photo`, `date`, `resized_photo`, `id_fuel`, `id_brand`)
VALUES ('".$model."','".$year."','".$price."','".$picture."','".$date."','".$resized."','".$fuels."','".$brand."')";
$this->db->query($sql1);
return $this->db->insert_id();
}
I print it with print_r($date) and it displays 2016-03-16, I really dont now why it wont insert like everything else.
Table structure
I just tried this minutes ago and it worked! ^_^
$d = date("Y-m-d");
$t = date("h:i:s");
$this->db->set($this->col_prefix.'customer_id', $_POST['customer_id']);
$this->db->set($this->col_prefix.'total_amount', $_POST['total_amount']);
$this->db->set('date', "'".$d."'");
$this->db->set('time_in', "'".$t."'");
$this->db->set('status', 1);
$this->db->insert('sln_transactions');
but haven't tried it yet in array :) hope this could help.
Please check data-type of 'date' column in database table. Might be possible issue.
Try these functions :
date('Y/m/d');
date('h-m-s');
date('Y/m/d:h-m-s');
I used these in particular to get the date and time. Might help you as well.
Make your query like this. Use DATE(".$date.")
$sql1="INSERT INTO `ads`(`model`, `year`, `price`, `photo`, `date`, `resized_photo`, `id_fuel`, `id_brand`)
VALUES ('".$model."','".$year."','".$price."','".$picture."',DATE(".$date."),'".$resized."','".$fuels."','".$brand."')";
Change your insert_ad function as below:
$sql1="INSERT INTO `ads`(`model`, `year`, `price`, `photo`,`resized_photo`, `id_fuel`, `id_brand`,`date`) VALUES ('".$model."','".$year."','".$price."','".$picture."','".$resized."','".$fuels."','".$brand."',NOW())";
$this->db->query($sql1);
return $this->db->insert_id();
Also remove the date parameter in controller function call and model function definition.
Please try this:
Controller:
$date=date("Y-d-m");
$succes=$this->pl->insert_ad(array(
'model'=>$model,
'id_brand'=>$brandID,
'price'=>$price,
'photo'=>$picture,
'date'=>$date,
'resized_photo'=>$resized,
'id_fuel'=>$id_usera,
'year'=>$year));
Model:
public function insert_ad($data) {
$this->db->insert('ads', $data);
return $this->db->insert_id();
}
Change From
$date=date("Y-d-m");
To
$date=date("Y-m-d");
And remvoe ' from integer type
public function insert_ad($brand,$model,$price,$year,$picture,$resized,$fuels,$date)
{
$sql1="INSERT INTO `ads` (`id_ad`, `model`, `year`, `price`, `photo`, `date`, `resized_photo`, `id_fuel`, `id_brand`) VALUES (NULL, '$model', '$year', '$price', '$picture', '".date('Y-m-d')."', '$resized', '$fuels', '$brand')";
$this->db->query($sql1);
return $this->db->insert_id();
}
**ANSWER **
*The correct formats of date * $date=date("Y-m-d"); *and * $date = date("Y-d-m"); as well
public function insert_ad($brand,$model,$price,$year,$picture,$resized,$fuels,$date)
{
$sql1="INSERT INTO `ads` (`id_ad`, `model`, `year`, `price`, `photo`, `date`, `resized_photo`, `id_fuel`, `id_brand`) VALUES (NULL, '$model', '$year', '$price', '$picture', '".date('Y-m-d')."', '$resized', '$fuels', '$brand')";
$this->db->query($sql1);
return $this->db->insert_id();
}
Try by using type varchar in your database structure for date.
CONTROLLER
$date=date("Y-m-d");
Database date format is Y-m-d not Y-d-m
this work perfect for me
in controller function
$this->model_invoice->invoice_create();
in model
$invoice_date = strtotime($this->input->post('invoice_date_time'));
$date=date("Y-m-d", $invoice_date);
$data = array
(
'invoice_date_time' => $date,
);
$this->db->insert('your_table_name', $data);
try this
in your Controller delete your variable $data
and also in your model delete the variable
model
public function insert_ad($brand,$model,$price,$year,$picture,$resized,$fuels)
{
$sql1="INSERT INTO `ads`(`model`, `year`, `price`, `photo`, `resized_photo`, `id_fuel`, `id_brand`)
VALUES ('".$model."','".$year."','".$price."','".$picture."','".$date."','".$resized."','".$fuels."','".$brand."')";
$this->db->query($sql1);
return $this->db->insert_id();
}
and also in your db change
type as DATETIME and
PREDETERMINATED as CURRENT_TIME
and run it
hope this works!
Related
I have a date field with CURRENT_TIMESTAMP attribute. and I am trying to insert date in the database but the value storing as '0000-00-00 00:00:00'.
My code:
<?php
if (isset($_POST['submit'])) {
$amount = $_POST['amount'];
$sql = "insert into `od_request` (`username`, `amount`, `status`, `date`) values ('$login_session', '$amount', 'Request', 'NOW()')";
$retval = mysql_query($sql);
if($retval) {
$success= "OD Request Sucessfully Sent!";
} else {
$error = "Sorry! Make sure you have entered all the Fields Correctly.";
}
}
?>
Use this request :
INSERT INTO `od_request` (`username`, `amount`, `status`, `date`) VALUES('$login_session', '$amount', 'Request', NOW())
You don't need to put ' around NOW() because is an SQL function
Syntax to insert date is wrong:
use NOW() not 'NOW()'
$sql = "insert into `od_request` (`username`, `amount`, `status`, `date`) values ('$login_session', '$amount', 'Request', NOW())";
date("Y-m-d H:i:s") is the MySQL datetime format
eg.
$sql = "insert into `od_request` (`username`, `amount`, `status`, `date`) values ('$login_session', '$amount', 'Request', '".date("Y-m-d H:i:s")."')"
what about this?
$sql = "insert into 'od_request' ('username', 'amount', 'status', 'date') values ('$login_session', '$amount', 'Request', NOW())"
I have this code:
$date = '1991-08-13';
$sql = "INSERT into TABLEA
(nombre, apellido1, apellido2, direccion, codigoPostal,fechaNacimiento, notas)
VALUES
('agds', 'asdgff', 'gerth', 'dfghdfghd efdgvwr', 86486, $date, 'ShhhHH');";
My problem is the next one:
When I insert that $date's value is: 1991-13-08 but in the DB appears: 0000-00-00
I've seen other posts with solutions like: STR_TO_DATE() and it dosen't work for me, it inserts NULL. Any other solution?
EDIT: missing: '' in $date (it should have been: '$date') Thanks for the correction! (:
Please enclose the $date with single quotes like
$sql = "INSERT into TABLEA (nombre, apellido1, apellido2, direccion, codigoPostal,fechaNacimiento, notas) VALUES ('agds', 'asdgff', 'gerth', 'dfghdfghd efdgvwr', 86486, '$date', 'ShhhHH');";
Maybe you can try by this way:
$date = '1991-08-13'; //yyyy-mm-dd
$sql = "INSERT into TABLEA
(nombre, apellido1, apellido2, direccion, codigoPostal,fechaNacimiento, notas)
VALUES
('agds', 'asdgff', 'gerth', 'dfghdfghd efdgvwr', 86486, '$date', 'ShhhHH');";
use Str_to_date
Str_to_date('1991-13-08','%Y-%d-%m')
or try this :-
$sql = "INSERT into TABLEA (nombre, apellido1, apellido2,
direccion, codigoPostal,fechaNacimiento, notas)
VALUES ('agds', 'asdgff', 'gerth', 'dfghdfghd efdgvwr',
86486, Str_to_date("1991-13-08","%Y-%d-%m"), 'ShhhHH');";
I am using to add data into DB. First i get the values from post and then insert it into table. The problem is that there are total 7 values but only 5 values added and 2 of them not inserted into the table. Here is my code
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] )) {
$degree_title = $_POST['degree_title'];
$degree_year = $_POST['degree_year'];
$uni_name = $_POST['uni_name'];
$degree_level = $_POST['degree_level'];
$major_sub = $_POST['major_sub'];
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
}
I echo the all values and all values are coming so why they all not inserted into table any idea. Thank
try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, '$eme_uid', '$degree_title', '$degree_year', '$degree_level', '$major_sub', '$uni_name')");
and i would highly recommend:
1) dont use mysql_ its deprecated, use mysqli_*
2) sanitze ALL values in _POST befor using in SQL statements.
if id is autoincrement then you dont need to insert it.
try this
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES ($eme_uid, $degree_title, $degree_year, $degree_level, $major_sub, $uni_name)");
My guess is that $degree_title and $uni_name doesn't get inserted because they are varchars. In that case you will have to put quotes around these values.
Mysql is kind of "forgiving" in the sence that it does not throw an error when using incorrect types in the sql-statement in relation to the actual type of the column.
Try:
$run = mysql_query("INSERT INTO `career_fourudb`.`tffeck_employee_edu` (`id`, `employee_id`, `degree`, `year`, `degree_level`, `major_degree`, `uni`)
VALUES (NULL, $eme_uid, '$degree_title', $degree_year, $degree_level, $major_sub, '$uni_name')");
As mentioned before id doesn't have to be included (if id-column is autoincremental) in the insert-statement, and you should really learn mysqli or PDO.
i have a db query in php that is not inserting into database. Have used this format lots of times but for some reason its not working now. any ideas please
$query = "INSERT INTO `databasename`.`member_users` (`id`, `first_name`, `last_name`, `username`, `password`, `address1`, `address2`, `postcode`, `access`, `expires`) VALUES (NULL, '$fname', '$lname', '$email', '', '$add1', '$add2', '$postcode', '0', '')";
$result = mysql_query($query);
if($result){
echo"query inserted";
}else{
echo "nope";
}
Instead of echo "nope"; I suggest something like :
echo 'error while inserting : ['.mysql_errno().'] '.mysql_error();
echo 'query : '.$query;
This way you will be able to see the exact error and the query that was executed.
It can be a lot of things :
Constraint error with a foreign key
Data type error
Non-existent field
Wrong database or table name
Instead of...
$query = "INSERT INTO `databasename`.`member_users` ..."
do
$query = "INSERT INTO member_users ..."
Hope it works. :)
If databasename and member_users are variables then,
Instead of
$query = "INSERT INTO databasename.member_users...
do
$query = "INSERT INTO $databasename.$member_users...
I have a strange problem, I'm sending an SQL query through PHP:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
And it throws me this error:
Invalid query: Column count doesn't match value count at row 1.
Although, when I paste and run the same exact query in PhpMyAdmin, it works perfectly, so it got me quite confused...
I counted the number of columns and the the number of values, and they match (19). I tried to remove the 'id' field, since it's auto-incremented, but it didn't change anything. What am I doing wrong? And why does it work in PhpMyAdmin?
Thanks for any help!
EDIT:
here's the php code:
$values = array('', 1, $lastUpdated, $entry_date, $entry_ip, $streetName, $cityId, $listing['stateorprovince'], $listing['postalcode'], $listing['type'], $listing['listprice'], $has_garage, $has_indoor_parking, $has_outdoor_parking, $has_pool, $has_fireplace, $average_nb_room, $listing['yearbuilt'], $listing['exteriortype']);
$q = "INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('".htmlentities(implode("','",$values),ENT_QUOTES)."')";
$this->execMysqlQuery($q);
and the method that is being called:
private function execMysqlQuery($q, $returnResults = false, $returnInsertId = false){
$c = mysql_connect(DB_SERVER,DB_LOGIN,DB_PASSWORD);
mysql_select_db(DB_NAME, $c);
$result = mysql_query($q);
if (!$result) {
die('Invalid query: ' . mysql_error(). "<br/>=>".$q);
}
if ($returnInsertId)
return mysql_insert_id();
mysql_close($c);
if ($returnResults)
return $result;
return true;
}
And the error:
Invalid query: Column count doesn't match value count at row 1
=>INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`) VALUES ('','1','2010-10-27 13:47:35','2010-10-27 13:47:35','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding')
If you print $q, I'm willing to bet it'll look like this:
INSERT INTO `lib_plex` (`id`, `active`, `lastUpdated`, `entry_date`, `entry_ip`, `address`, `city`, `state_iso`, `zip_code`, `plex_type`, `price`, `has_garage`, `has_indoor_parking`, `has_outdoor_parking`, `has_pool`, `has_fireplace`, `average_nb_room`, `construction_year`, `building_material`)
VALUES ('','1','2010-10-27 13:22:59','2010-10-27 13:22:59','2130706433','COMMERCE ST.','85825','OK','73521','commercial','595000','0','0','0','0','0','11','','Aluminum Siding');
(I don't have PHP at work; this is a guess)
In other words, htmlentities is turning your quotes into HTML Entities. Specifically, turning ' to '
Don't use htmlentities on things that aren't being sent to the web browser. Use your database driver's escaping method (mysql_real_escape_string) on each individual value being sent in.
Edit: Better yet, use prepared statements and data binding with MySQLi or PDO, which will automatically escape the data as you bind it.
if ($insert) {
$query = "INSERT INTO employee VALUES ($empno,'$lname','$fname','$init','$gender','$bdate','$dept','$position',$pay,$dayswork,$otrate,$othrs,$allow,$advances,$insurance,'')";
$msg = "New record saved!";
}
else {
$query = "UPDATE employee SET empno=$empno,lname='$lname',fname='$fname',init= '$init',gender='$gender',bdate='$bdate',dept='$dept',position='$position',pay=$pay,dayswork=$dayswork,otrate=$otrate,othrs=$othrs,allow=$allow,advances=$advances,insurance=$insurance WHERE empno = $empno";
$msg = "Record updated!";
}
include 'include/dbconnection.php';
$result=mysql_query ($query,$link) or die ("invalid query".mysql_error());