mysql update statement changed my parameter value - php

I have a php script which accepts a couple of parameters and invoke a mysql update. One of the parameters is an integer. I added breaker point before the mysql update statement is executed and used var_dump. It showed int(5) but when I verified the result in the database, the value of the updated column show 2016. The column was defined as INT(11). I tried to change the column to be tinyint and the value after update became 127. Can anyone tell me what did I do wrong?
<?php
header('Location: upd_shpsts.php?shpid=87&stsdesc=abc&stsdate=02/10/2016 4:42PM&ctyid=5');
?>
function UpdShpSts($shpid, $stsdesc, $stsdate, $ctyid) {
$ctyid=intval($ctyid);
var_dump($ctyid);
$usrid = $_SESSION['usr_id'];
$pkgs = array();
$pkgs_query = mysql_query("SELECT pkgid FROM pkg WHERE shpid='$shpid'") or die(mysql_error());
while ($pkg_rows = mysql_fetch_assoc($pkgs_query)) {
$pkgs[] = array(
'pkgid' => $pkg_rows['pkgid']
);
}
if (!empty($pkgs)) {
foreach ($pkgs as $pkg) {
$pkgid = $pkg['pkgid'];
$timestamp = strtotime($stsdate);
$statusdate = date("Y-m-d H:i:s", $timestamp);
mysql_query("INSERT INTO pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat) VALUES('$pkgid', '$stsdesc', '$ctyid', '$statusdate', '$usrid', now())") or die(mysql_error());
}
}
}

You switch the columns around in your update statment
"INSERT INTO
pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat)
VALUES('$pkgid', '$stsdesc', '$ctyid', '$statusdate', '$usrid', now())")
Lining your query up like above makes it obvious. Switch $ctyid and $statusdate
"INSERT INTO
pkgsts (pkgid, stsdesc, stsdate, ctyid, lastchgby, lastchgat)
VALUES('$pkgid', '$stsdesc', '$statusdate', '$ctyid', '$usrid', now())")
So you were trying to insert 2016-10-02 <time> into an INT field, so MySQL did its best to turn it into an INT, and you ended up with 2016

Related

using mysql NOW() function to update row in database not working in PHP query

I am trying to use the NOW() mysql function to update the datetime column for an inserted row. The datetime column is called 'transaction'. I tried finding a similar PHP function to mirror/mimic the datetime format but couldn't find one suitable.
$purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, `transaction`, `transType`) VALUES ((?),(?),(?),(?),(?)) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,NOW(),"BUY");
You can use PHP date function:
date("Y-m-d H:i:s")
to put current time
or you can not bind the parameter:
$purchase = query("INSERT INTO `Portfolio`(`id`, `symbol`, `shares`, transaction`, `transType`) VALUES (?,?,?,NOW(),?) ON DUPLICATE KEY UPDATE shares = shares + VALUES(shares)",$user,$symbol,$shs,"BUY");
The NOW() goes in place of one of the "?", not in the bind list.
If you also wanted to update that field in case the statement turns into an UPDATE, then you need it in the SET also.
$database = new database;
$now = $database->now();
class database {
...
public function now($query = "SELECT NOW();"){
$sth = $this->connect->prepare($query);
// execute
if ($sth->execute()) {
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result["NOW()"];
} else {
echo "\nPDO::errorInfo():\n";
print_r($sth->errorInfo());
echo "\nQuery:\n";
echo $query;
echo "\nParam:\n";
}
}
}

MySQL - Compare all values in a column and write in another column

I need to create a script that compares one field in the database (has a date stored, it's type is "TEXT" and cannot be changed DATE) to the current server date.
The dates are encoded like this "1380571547", so i need to use strftime() to decode them. This field for example, decoded with strftime corresponds to this "Sep-30-2013, 22:05"
What I need is to compare those fields with the current date, and according to that condition, write something like "Expired" in another field.
To achieve this, I made this block of code:
<?php
require("connection.php");
$today = strftime('%b-%d-%Y, %H:%M');
$exp_date = mysql_query("SELECT numbers FROM date");
while($row = mysql_fetch_array($exp_date))
{
echo (strftime ( '%b-%d-%Y, %H:%M', $row ['numbers'])). "<br />";
}
if ($exp_date < $today) {
$sql = "INSERT INTO date (changed) VALUES ('EXPIRED')";
$result = mysql_query($sql);
echo "ADDED!";
}
?>
However, this code is not working, can someone help me ?
PHP is not my strong point but it looks to me like you condition is doing a comparison on an array,
IE:
if ($exp_date < $today) // will always be false.
Your code would probably have to look something more like this.
while($row = mysql_fetch_array($exp_date))
{
if ($row[0] < $today)
{
$sql = "Update date set changed = VALUE where rowid = rowid";
$result = mysql_query($sql);
echo "ADDED!";
}
}
having said that i would probably do the comparison and update in SQL using a case statement,
Update Date
set changed = case when number > ExpiryDate
then "Expired"
else "Current"
end
You can do all this in a single query:
UPDATE `date` set `changed`='Expired' where date(now()) > date(from_unixtime(`numbers`))
But this is not what your code is attempting to do. Your second block seems to be inserting the word Expired in new rows, rather than updating anything.
Note that the table name date should be wrapped in backticks to avoid any possible clash with MySQL keywords
I don't understand the second block of code with the insert. I would do an update inside the loop. but if your going to do that, it could probably be done in one combined update statement.

How to avoid duplicate entry in mysql with php

Here i have made a function to produce random key,
function gen_link(){
$link = '';
$s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
for ($i= 0 ; $i <= 4 ; $i++)
$link = $link.$s[rand(0,63)];
return $link;
}
I dont want to repeat the key in mysql table, i have made it unique in mysql, but what i want to do is, when the key already exists i want to regenerate another random key and try to add it to table again, i tried this code below.
$con = mysqli_connect("localhost","shashi","asd123","redir");
$sql = " insert into 'links' ('link') values('$link') ";
do{
$link = gen_link();
$result = mysqli_query($con,$sql);
}while(mysqli_errno($con)==1064);
mysqli_close($con);
but it doesn't seem to work at all, it keeps looping. what can i do?
Instead of generating an actual error, use an INSERT IGNORE query like this:
$sql = "insert ignore into `links` (`link`) values ('$link')";
And check mysqli_affected_rows() to ensure something was actually inserted:
while (mysqli_affected_rows($con) == 0);
All together, that looks like this:
$con = mysqli_connect("localhost", "shashi", "asd123", "redir");
do {
$link = gen_link();
$sql = "insert ignore into `links` (`link`) values ('$link')";
$result = mysqli_query($con, $sql);
} while (mysqli_affected_rows($con) == 0);
mysqli_close($con);
Also, a couple notes about your queries:
I changed your quotes around the table and column names to backticks, which is the correct way to quote them in sql.
Because you're including the $link variable directly in the query, you need to define your query after you give the $link variable a value - so I moved that line inside the loop. This is probably the source of your original problem where you kept looping.
It's not important in this instance because you have full control of the value you're inserting (generated in gen_link()), but it's a good idea to get in the habit of properly escaping the variables you insert into a query. Alternatively, read up a bit on prepared statements, and use them instead.
Get the existing key values from the DB as array. Then search your current key with your existing keys using in_array() function. If it is true generate new key. If the condition is false , insert your new key.
http://php.net/manual/en/function.in-array.php
if(in_array($new_key,$existing))
{
//generate new key
}
else
{
//insert current key
}
I'm working with Prepared Statement an using "ON DUPLICATE KEY", to change the duplicate Value with MYSQL:
$sql = "INSERT INTO ".$this->table." ".
"(".implode(',',$fields).") VALUES
(".implode(',',$values).")
ON DUPLICATE KEY
UPDATE key_field = concat(substr(key_field,1,".($laenge_key-3)."),FORMAT(FLOOR(RAND()*999),0))

Mysql PDO prepare statement issue with DATE data type

I have trouble with date data type.
I have a php mysql pdo statement:
$mystmt = $mydb->prepare("
SELECT `ad_id`
FROM `tbl_actions`
WHERE
(`actiondate` > :nowcookietime )
");
$mystmt->execute(array(
':nowcookietime'=>date("Y-m-d H:i:s", time()-$cookiedurationlock),
)
);
$testnotinsql = $mystmt->fetch(PDO::FETCH_ASSOC); // EMPTY
The code run return empty. But if i get the sql below from general_log and run in sql tool (HeidiSQL), it will return record.
SQL from general_log:
SELECT ad_id
FROM tbl_actions
WHERE
(actiondate> '2012-08-24 17:53:21' )
My PHP timezone is UTC+7
Mysql is SYSTEM (which UTC)
As I understand it's not timezone problem if insert and query in php using same timezone.
I test the bind parameter with force string
':nowcookietime'=>date("Y-m-d H:i:s", time()-$cookiedurationlock),
but it's same empty.
BUT: if use quote then it return rows
':nowcookietime'=>"'".date("Y-m-d H:i:s", time()-$cookiedurationlock)."'",
Can you clarify what wrong with this statement as I understand we dont need quote, mysql pdo quote for us.
EDIT 1:
I update the correct sql. With quote in sql is my mistake when take from test. The without quote around :nowcookietime stil empty.
CLOSED
See my answer below.
As N.B. said in the comment use
(actiondate > :nowcookietime)
without the single-quotes around :nowcookietime in the sql statement.
Self-contained example:
<?php
$mydb = setup();
$cookiedurationlock = 40;
$mystmt = $mydb->prepare("
SELECT `ad_id`
FROM `tmp_tbl_actions`
WHERE
(`actiondate` > :nowcookietime )
");
$mystmt->execute(array(
':nowcookietime'=>date("Y-m-d H:i:s", time()-$cookiedurationlock),
));
$testnotinsql = $mystmt->fetch(PDO::FETCH_ASSOC);
var_dump($testnotinsql);
function setup() {
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('
CREATE TEMPORARY TABLE tmp_tbl_actions (
ad_id int auto_increment,
actiondate DATETIME,
primary key(ad_id),
key(actiondate)
)
');
$stmt = $pdo->prepare('INSERT INTO tmp_tbl_actions (actiondate) VALUES(?)');
$t = time();
for($i=-80; $i<10; $i++) {
$stmt->execute(array(date('Y-m-d H:i:s', $t+$i)));
}
return $pdo;
}
prints
array(1) {
["ad_id"]=>
string(2) "42"
}
The colon in
':nowcookietime'=>date(...
is probably superfluous, but it's also used in Example #2 at http://docs.php.net/manual/en/pdostatement.execute.php
I find out why.
Basicly there's script set the $cookiedurationlock too short, so most the time it empty.
When add quote, the comparation will be (actiondate > '\'2012-08-25 02:28:22\'' ), so it will return rows.
After the query, there is a insert new action row. So when i run trace sql from tools, data was change and it return the new one which added after this sql.
I think I have to organize my script to simpler ones.
Thanks all for your help.

Wrong mysql query in php file?

I'm trying to insert some data into my mysql database. The connection is working fine but im having a problem with sending the query correctly to the database. Below you can find the code in my php file. I also post what for type of fields they are in the Database.
Fields in the mysql database:
Reservaties_id = int
Materialen_id = int
aantal = int
effectief_gebruikt = tinyint
opmerking = Varchar2
datum_van = date
datum_tot = date
$resID = $_REQUEST['resID'];
$materialen_id = $_REQUEST['materialen_id'];
$aantal = $_REQUEST['aantal'];
$effectief_gebruikt = $_REQUEST['effectief_gebruikt'];
$opmerking = $_REQUEST['opmerking'];
$datum_van = date('YYYY-MM-DD',$_REQUEST['datum_van']);
$datum_tot = date('YYYY-MM-DD',$_REQUEST['datum_tot']);
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`, `materialen_id`, `aantal`, `effectief_gebruikt`, `opmerking`, `datum_van`, `datum_tot`) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', $datum_van, $datum_tot)";
mysql_query($string);
you have to include single quotes for the date fields '$dataum_van'
$string = "INSERT INTO `materialen_per_reservatie`(reservaties_id, materialen_id, aantal, effectief_gebruikt, opmerking, datum_van, datum_tot) VALUES ($resID, $materialen_id, $aantal, $effectief_gebruikt, '$opmerking', '$datum_van', '$datum_tot')";
and this is only a example query, while implementing don't forget to sanitize your inputs
Your code has some serious problems that you should fix. For one, it is not doing any error checking, so it's no surprise the query breaks silently when it fails. Check for errors and it will tell you what goes wrong - how to do it is outlined in the manual on mysql_query() or in this reference question.. Example:
$result = mysql_query($string);
// Bail out on error
if (!$result)
{
trigger_error("Database error: ".mysql_error(), E_USER_ERROR);
die();
}
In this specific case, I'm fairly sure it's because you are not putting your values into quotes after the VALUES keyword.
Also, the code you show is vulnerable to SQL injection. You need to escape every value you use like so:
$resID = mysql_real_escape_string($_REQUEST['resID']);
for this to work, you need to put every value in your query into quotes.
try this
$string = "INSERT INTO `materialen_per_reservatie`(`reservaties_id`) VALUES ('".$resID."')";

Categories