MYSQL select where timestamp data not retrieve - php

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.

Related

How to set automatically id base on date

I'm a newbie in PHP. I hope someone can help me. before that sorry my english's bad.
I want set kd_transaksi base on date and id from another table. when people booking, system automatically set kd_transaksi.
$tgl_pesan = date("Ymd");
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
$row = mysqli_fetch_array($cek);
$kdMax = $row['kode'];
$nourut = substr($kdMax, 8, 4);
$nourut++;
$char = "BO";
$kd_transaksi = $char.$tgl_pesan.printf('%04s', $nourut);
$kd_booking = mysqli_insert_id($conn);
$book = "INSERT INTO detail_booking (kd_booking,kd_transaksi,total_bayar) VALUES ('".$kd_booking."','$kd_transaksi',$total_bayar')";
$ok = mysqli_query($conn,$book);
if ($ok) {
header('location:../mybooking.php');
} else{
mysqli_close($conn);
}
but result in query $cek is NULL.
$cek = mysqli_query($conn, "SELECT max(kd_booking) AS kode FROM booking WHERE kd_booking LIKE '$tgl_pesan%'");
how do I fix it?
booking table
CREATE TABLE `booking` (
`kd_booking` int(11) NOT NULL,
`id_user` int(11) NOT NULL,
`kd_paket` int(11) NOT NULL,
`jml_org` int(11) NOT NULL,
`tgl_pesan` date NOT NULL,
`tgl_wisata` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
What i want is
If someone booking today and get kd_booking 21, then the output would be : BO2018120521.
First of all, you have something wrong with your CREATE TABLE. When you create a table you should have an AUTOINCREMENT primary key, this is your id. So it would be something like this:
CREATE TABLE `booking` ( `id` INT NOT NULL AUTO_INCREMENT , `id_user` INT(11) NOT NULL , `kd_paket` INT(11) NOT NULL , `jml_org` INT(11) NOT NULL , `tgl_wisata` DATE NOT NULL , `tgl_pesan` DATE NOT NULL , PRIMARY KEY (`id`)) ENGINE = InnoDB;
As i can se you have two errors:
Date should be like date('Y-m-d') http://php.net/manual/en/function.date.php
You're trying to insert an int value like '".$kd_booking."' when that just works for strings.
Hope it helped.

foreach with mysqli_multi_query issue

I have the below code which works fine and updates each record contained in the array:
$check_list = isset($_POST['check_list']) ? $_POST['check_list'] : array();
foreach($check_list as $check_list) {
$query = "UPDATE `stock` SET `signature_id` = 0,
user_id = 0,
`status_id` = 1
WHERE `id` = '$check_list'";
$result = mysqli_query($conn, $query);
I now need it to execute multiple queries for each result in the array so I have changed the code to the following using mysqli_multi_query:
$check_list = isset($_POST['check_list']) ? $_POST['check_list'] : array();
foreach($check_list as $check_list) {
$query = "UPDATE `stock` SET `signature_id` = 0,
user_id = 0,
`status_id` = 1
WHERE `id` = '$check_list';
INSERT INTO `returned`
(`id`, `stock_id`, `signature_id`,
`user_id`, `timestamp`)
VALUES ('','$check_list','$id',
'$user_id',now())";
$result = mysqli_multi_query($conn, $query);
But it now only executes one UPDATE and one INSERT for the first record in the array, and ignores the others
#RiggsFolly is giving the best advice about prepared parameterised statements and transactions due to re-usability and security, but if you want/need to stay with mysqli_multi_query, (because you don't want to transition to a new querying process mid-project or because it is otherwise unappealing to you) here is how mysqli_multi_query can serve you:
Query Combination:
If the SET values stay the same and only the id's are different, all UPDATE queries can be merged into a single query. If the values are static you can use implode(), if not you can chose between using a (verbose/ugly) CASE statement in the SET clause of a single query, or create multiple UPDATE queries as in your original post.
$queries="UPDATE `stock` SET `signature_id`=0,`user_id`=0,`status_id`=1 WHERE `id` IN (".implode(',',$check_list).");";
Likewise with the INSERT queries, they can all be merged into one statement with implode() or a foreach loop that only extends the VALUE portion.
$queries.="INSERT INTO `returned` (`stock_id`,`signature_id`,`user_id`,`timestamp`) VALUES ('".implode("','$id','$user_id',now()),('",$check_list)."','$id','$user_id',now());";
or
$queries.="INSERT INTO `returned` (`stock_id`,`signature_id`,`user_id`,`timestamp`) VALUES ";
foreach($check_list as $k=>$check_list){
// manipulate $id and $user_id as needed
$queries.=($k==0?"":",")."('$check_list','$id','$user_id',now())";
}
Failure Awareness:
If you don't need any kind of indication of success then a one-liner will do (keep this outside of any loops of course):
mysqli_multi_query($conn,$queries)
otherwise, you'll need a slightly larger block of code:
if(mysqli_multi_query($conn,$queries)){
do{
echo "<br>Rows = ",mysqli_affected_rows($conn);
} while(mysqli_more_results($conn) && mysqli_next_result($conn));
}
if($mysqli_error=mysqli_error($conn)){
echo "<br>Syntax Error: $mysqli_error";
}
I have tested my solution using implode() for both queries and was successful using:
$check_list=array(1,3,5,6,10,11);
and a database setup of:
CREATE TABLE `stock` (
id int(10) NOT NULL AUTO_INCREMENT,
signature_id int(10) NOT NULL,
user_id int(10) NOT NULL,
status_id int(10) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE `returned` (
id int(10) NOT NULL AUTO_INCREMENT,
stock_id int(10) NOT NULL,
signature_id int(10) NOT NULL,
user_id int(10) NOT NULL,
`timestamp` datetime NOT NULL,
PRIMARY KEY (id)
);
/* Declaring your `id` columns with AUTO_INCREMENT means you can omit them from your INSERT query. */
/* Depending on your mysql version, creating a default datetime for `timestamp` may be possible which then would permit omitting `timestamp` from your INSERT query too. */
INSERT INTO `stock` (`signature_id`,`user_id`,`status_id`) VALUES
(1,1,1),
(2,2,2),
(3,3,3),
(4,4,4),
(5,5,5),
(6,6,6),
(7,7,7),
(8,8,8),
(9,9,9),
(10,10,10),
(11,11,11),
(12,12,12);
The built query looks like this:
UPDATE `stock` SET `signature_id`=0,`user_id`=0,`status_id`=1 WHERE `id` IN (1,3,5,6,10,11);INSERT INTO `returned` (`stock_id`,`signature_id`,`user_id`,`timestamp`) VALUES ('1','','',now()),('3','','',now()),('5','','',now()),('6','','',now()),('10','','',now()),('11','','',now());

Get a record with maxid and condition in mysql in yii, but sometime it get second record?

my table:
CREATE TABLE IF NOT EXISTS `the_kho_chi_tiet_with_id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ngay_thang` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ma_phieu` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`id_san_pham` int(11) NOT NULL,
`id_kho` int(11) NOT NULL,
`khoi_luong_nhap` double NOT NULL,
`so_luong_nhap` int(11) NOT NULL,
`khoi_luong_xuat` double NOT NULL,
`so_luong_xuat` int(11) NOT NULL,
`khoi_luong_ton` double NOT NULL,
`so_luong_ton` int(11) NOT NULL,
`kho_du_tru` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
PHP code:
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
**Get a record with maxid and condition in mysql in yii, *but sometime it get second record* !?**
Please check with the below, hope it works!..if not please tell...
$id_kho=373;//sample value declaration
$id_san_pham=1;//sample value declaration
$select="select max(id) as id,so_luong_ton, khoi_luong_ton, kho_du_tru from
the_kho_chi_tiet_with_id where users_ref_id=".$id_kho." and
status=".$id_san_pham;
$command = Yii::app()->db->createCommand($select)->queryRow();
$Maxid=$command['id'];
$so_luong_ton=$command['so_luong_ton'];
$khoi_luong_ton=$command['khoi_luong_ton'];
$kho_du_tru=$command['kho_du_tru'];
I think, the problem is conflict. It mean that when I get record have max_id, and then before i insert new record, having another process insert new record was inserted.
if such cases happen, so how to handle to fix above problem?
My solution:
$lock = $connection->createCommand('LOCK TABLES `the_kho_chi_tiet_with_id` READ');
$lock->execute();
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
//Insert new record here
TheKhoChiTietWithId::model()->InsertNewRecord(1,300,1,333,1);
$unlock = $connection->createCommand('UNLOCK TABLES');
$unlock->execute();
I lock table to keep no other session work to this table.

SQL Insert Date Always comes out NULL

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

MySQL fulltext basic search, multiple words

I have the following code:
$dbLink = mysql_connect('localhost', 'tester', 'test');
mysql_select_db('acianetm_pcSpec', $dbLink);
$q = $_GET['q'];
$q = mysql_real_escape_string($q);
$sql = "
SELECT *,
MATCH(part) AGAINST ('$q') AS score
FROM parts
WHERE MATCH(part) AGAINST('$q')
";
$rest = MySQL_query($sql);
while($row = MySQL_fetch_array($rest)) {
echo "<br /> <strong>".$row['id']. " - ". $row['part']. " - $". $row['price']."</strong>";
}
When I load up http://site.com/q?=Nvidia it does not display any output.
MySQL Structure:
CREATE TABLE `parts` (
`id` int(10) NOT NULL auto_increment,
`part` varchar(512) NOT NULL,
`price` varchar(15) NOT NULL,
`updated` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `part_2` (`part`),
FULLTEXT KEY `part` (`part`)
) ENGINE=MyISAM AUTO_INCREMENT=47 DEFAULT CHARSET=latin1
The data inside the table:
`id |#| part |#| price
46 |#| (VIC Clayton Clearance) GIGABYTE 9800GT 512MB Nvidia Geforce GF9800GT DVI P... |#| 95.00
I have tried this SQL query:
SELECT * FROM parts WHERE part LIKE '%$q%'
However without using str_replace eg.
str_replace(' ', '&'. $q); it never worked for multiple words. Using the str_replace only made it work with 2 words, I need multiple.
Doing this in PHPMyAdmin returns no rows either, so what part of the query is wrong?
If someone could assist that would be great.
Thanks alot
Omit the where clause in your sql statement.
Also the '?' in your URL should come before any name value pairs.
$sql = "SELECT * FROM parts
WHERE MATCH(part) AGAINST ('$q')";
Works well :-)

Categories