Can not set a NOW() in datetime field mysql with php - php

Hello I'm having a hard time trying to update this field automatically when I update something else in that same table called 'reps' the structure of the table is:
id int primary key,
name varchar(10) not null,
date_up datetime
When I run this query:
SELECT * FROM reps;
it shows the information correctly however when I try to update a row of this table the date_up field is not updating... here's my code:
require dirname(__FILE__).'/db/connect.php';
$id = 5;
$name = "LCD Replacement";
$conexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $conexion->prepare('UPDATE reps SET name=:name, date_up = NOW() WHERE id = :id');
$statement->execute(array(
':name' => $name,
':id' => $id
));
when I refresh the page nothing is updated but if I run that same SQL query on the mysql console it work so I don't know what I'm doing wrong??

Related

Syntax error in SELECT query inside PHP script

I am trying to create a query inside a PDO script that checks if a record exists if it does the query should update the record and if it doesn't exist it should create a new one.
The column that should only exist once in the table is not an INDEX key (cannot make it unique right now) so it is not set as unique and I cannot use the ON DUPLICATE KEY UPDATE
I would like to use this queries logic below to make it work:
$stmt = $conn->prepare('IF EXISTS (SELECT * FROM `Table1` WHERE `code`= :code )
UPDATE `Table1`
SET `code_stat` = 2
WHERE code = :code
ELSE
INSERT INTO `Table1` (`code`,`code_stat`)
VALUES (:code, 2 ) ' );
$stmt->execute([
'code' => $_POST['code']
]);
The problem is when executing the query I get the following error saying there is a syntax problem:
SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near
'IF EXISTS (SELECT * FROM Table1 WHERE code= ? ) UPDATE Table1' at line 1
If you can't add a unique key to the table, you can attempt an update first, and if that doesn't update any rows, do an insert. Something like this:
$stmt = $conn->prepare('UPDATE `Table1` SET `code_stat` = 2 WHERE code = :code');
$stmt->execute(array(':code' => $_POST['code']));
if (!$stmt->rowCount()) {
// no rows updated, so insert
$stmt = $conn->prepare('INSERT INTO `Table1` (`code_stat`, `code`) VALUES (2, :code)');
$stmt->execute(array(':code' => $_POST['code']));
}
Note that you may need to set the PDO::MYSQL_ATTR_FOUND_ROWS attribute to ensure that the UPDATE query returns 1 if it finds the row but the value doesn't change. You must set that attribute when you make the connection e.g.
$conn = new PDO($dsn, $user, $pass, array(PDO::MYSQL_ATTR_FOUND_ROWS => true));
Why not write a stored procedure to handle this, similar to the below:
DROP PROCEDURE IF EXISTS db.SP_NEW_CODE;
CREATE PROCEDURE db.`SP_NEW_CODE`(IN `in_code` INT)
BEGIN
DECLARE numFound INT DEFAULT 0;
SET numFound=(SELECT * FROM `Table1` WHERE `code`= in_code);
IF (numFound=0) THEN
INSERT INTO `Table1` (`code`,`code_stat`) VALUES (in_code, 2 );
ELSE
UPDATE `Table1` SET `code_stat` = 2 WHERE code = in_code
END IF;
END;
From your code, simple execute CALL SP_NEWCODE(3); (for example, where 3 is the appropriate code value).

How to get a tuple's values that is inserted into PostgreSql db using php?

I am trying to insert a tuple into PostgreSql using PHP. After inserting the tuple I want to get the value of one of the columns of the inserted row. This column value is generated automatically by the db as it is defined as SERIAL in DDL.
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me')";
$result = pg_query($dbh,$query);
if (!$result) {
$status = 0;
} else {
$status = 1;
}
$row = pg_fetch_assoc($result);
$pID = $row['postID'];
$array = array(
'status' => $status,
'pID' => $pID
);
#Delete query is only for checking if the code is working.
$query = "DELETE FROM posts WHERE postID='$pID'";
$result = pg_query($dbh,$query);
The table 'posts' has following DDL:
CREATE TABLE posts
( title CHAR(20),
content CHAR(42),
x_coor INTEGER,
y_coor INTEGER,
userID CHAR(50),
time_stamp TIMESTAMP default current_timestamp,
postID SERIAL,
PRIMARY KEY(postID),
FOREIGN KEY (userID) REFERENCES users ON DELETE CASCADE);
I want to get the value of 'postID' column when I insert a row into the table 'posts' to perform additional functions based on postID. I have tried pg_fetch_assoc, pg_fetch_row, pg_fetch_object & pg_fetch_array. None of those seem to work. (I made appropriate modifications to the code when using each of those functions.)
Is there something incorrect in the code or perhaps I am missing something?
Thanks!
A good way is the returning clause:
INSERT INTO posts
VALUES('$title','$msg',$x,$y,'$me')
RETURNING id;
My PHP is a bit rusty, but it'd look something like:
$query = "INSERT INTO posts VALUES('$title','$msg',$x,$y,'$me') RETURNING id";
$result = pg_query($dbh, $query);
if ($result) {
$row = pg_fetch_row($result);
$inserted_id = $row[0];
}

PHP update mysqli only works until closing browser

I have a question about the update function in mysqli.
For school, I'm trying to create a click counter for my website which counts how many times a user has visited a certain page.
So far I've come up with this:
<?php
/*
* ToDo: Check why number of clicks goes back to two when completely
* refreshing page.
*
*/
include("init.php");
session_start();
//Count variable
$clicks = 0;
//Query for checking if there are any entry's in the database
$query = "SELECT * FROM `beoordelingen`.`clickcounter` WHERE `game_id`={$id}";
$result = $conn->query($query);
//If query returns false
if (!mysqli_num_rows($result)) {
//Create entry in database
$insert = "INSERT INTO `beoordelingen`.`clickcounter` (`ID`, `game_id`, `clicks`) VALUES (NULL, '1', '1');";
$createEntry = $conn->query($insert);
}
//If query returns true
else {
//Setting the number of clicks equal to $clicks
while ($data = $result->fetch_assoc()) {
$clicks = $data['clicks'];
}
//Insert new number into database
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$insertInto = $conn->query($sql);
//Echo current number of clicks
echo $clicks;
}
?>
The actual problem is that my update statement doesn't seem to work properly. If anyone would be able to spot why it doesn't work I'd be very happy.
The database is as following;
Beoordelingen <- Database
clickcounter <- Table which has the following three columns:
1. ID
2. game_id
3. clicks
The scripts does add an entry into the databse with click count 2. So when I reload the page it says 2. And when refreshing it counts up, but doesn't update the table.
Thanks! If anything is unclear please ask me!
Theoretically you should be able to do all of it in one query if game_id is unique.
Given the following table structure the sql query below will insert if the relevant record does not exists and then update if it does.
create table `clickcounter` (
`id` int(10) unsigned not null auto_increment,
`game_id` int(10) unsigned not null default '0',
`clicks` int(10) unsigned not null default '0',
primary key (`id`),
unique index `game_id` (`game_id`)
)
engine=innodb;
The trick is setting the indices on your table correctly ~ initially you don't know the value of the ID and I would guess that is an auto increment primary key? So, set a unique key on game_id...I hope it helps!
/* Could even change `clicks`='{$clicks}' to `clicks`=1 in initial insert */
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
<?php
include("init.php");
session_start();
/* Where / how is "$id" defined? */
/* insert new record / update existing */
$sql="insert into `clickcounter` set `clicks`=1, `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$result = $conn->query( $sql );
/* retrieve the number of clicks */
$sql="select `clicks` from `clickcounter` where `game_id`='{$id}';";
$result = $conn->query( $sql );
while( $rs=$result->fetch_object() ) $clicks=intval( $rs->clicks );
echo 'Total clicks: '.$clicks;
?>

UPDATE Query in Mysql Does not work

I have face a problem with my UPDATE Query in Mysql-
mysql_query( INSERT INTO `cost`
SET `cat_id` = '18', `feature_id` = '77', `type_id` = '5',
`cost_from` = '600', `cost_to` = '800'
WHERE `type_id` = 5 && `cat_id` = 18 && `feature_id` = 77");
type_id = 5 is not in my current table where i want to SET my new values.
The result is Unsuccessful.
I tried also an UPDATE query for the same
mysql_query( Update `cost`
SET `cat_id` = '18', `feature_id` = '77', `type_id` = '5',
`cost_from` = '600', `cost_to` = '800'
WHERE `type_id` = 5 && `cat_id` = 18 && `feature_id` = 77");
What should i do to insert and update values at the same time?
Note:
You don't use WHERE and SET on an INSERT query.
Make sure you have a table named cost along with the columns cat_id, feature_id, cost_from, cost_to, type_id.
You're trying to update the cost table columns with the ones you are looking for. Doesn't seem right.
Your first and second given sample codes have the same format, you just changed the first word, INSERT and UPDATE. Doesn't work that way.
You can, I think the recommendation of all people that would see your code, create better queries using mysql_* prepared statements.
A simple example of an INSERT query would look like this:
/* PREPARE YOUR QUERY */
$stmt = $con->prepare("INSERT INTO cost (cat_id, feature_id, type_id, cost_from, cost_to) VALUES (?,?,?,?,?)");
/* BIND PARAMETER TO THE QUERY. REPLACE NECESSARY VALUE OR VARIABLE */
$stmt->bind_param('iiiss', $catid,$featureid,$typeid,$costfrom,$costto);
$stmt->execute(); /* EXECUTE QUERY */
A simple example of an UPDATE query:
/* PREPARE YOUR QUERY */
$stmt = $con->prepare("UPDATE cost SET cat_id=?, feature_id=?, type_id=?, cost_from=?, cost_to=? WHERE id=?");
/* BIND PARAMETER TO THE QUERY. REPLACE NECESSARY VALUE OR VARIABLE */
$stmt->bind_param('iiissi', $catid,$featureid,$typeid,$costfrom,$costto,$id);
$stmt->execute(); /* EXECUTE QUERY */
First of all, you cannot use 'set ' with ' insert into' , and if you want to insert and update queries at the same time, then your best bet is using transaction . (you have to enclose insert and update queries in a transaction) , you cannot enclose both on a single sql statement..
This post might help you
SQL Update,Delete And Insert In Same Time

Last insert id issue--How to fetch it

I'm using $id = mysqli_insert_id($connection); to get the last inserted id, but in case if it updates any record in the table, it returns 0 as last inserted id.
Is there any way to handle this?
I want to get id each time weather it's inserting or updating.
Thanks
Edit
I need this id to be used for inserting data into table2
id from tab1
put data into tab2 where id from tab1 is FK
and most important, I'm not using the update with where clause
Here is my code that I'm using
$val = utf8_encode($val);
mysqli_set_charset($connection, 'utf8');
mysqli_query($connection, "SET NAMES 'utf8'");
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
$sql = "INSERT INTO leaks($insert) VALUES($val)";
$sql .= " ON DUPLICATE KEY UPDATE `url` = '".mysqli_real_escape_string($connection,$data['url'])."';";
mysqli_query($connection, ($sql))or die(mysqli_error($connection)."<br />".print($sql));
$id = mysqli_insert_id($connection);
$proofs['leaks_id'] = $id;
mysqli_query($connection, "SET FOREIGN_KEY_CHECKS = 0;");
print_r($id);
$this->insertProofs($connection, $proofs);
connection::close_connection($connection);
Please note down that $this->insertProofs($connection, $proofs); inserts data to table2 on the base of key passed to it
On INSERT
After executing an INSERT query, using mysqli_insert_id() is absolutely fine.
On UPDATE
Depending on your update, you;
Would know the id's you're updating
Know the criteria to search for the id's from the update.
For example, if your UPDATE was something like;
UPDATE `foo` SET `x`='y' WHERE `a`='b'
You can then run
SELECT `id` FROM `foo` WHERE `a`='b'
to fetch the updated id's.
Edit
I see you're using ON DUPLICATE KEY UPDATE.
You can modify your query to become (assuming id is the primary auto_increment key)
ON DUPLICATE KEY UPDATE
`url` = '".mysqli_real_escape_string($connection,$data['url'])."',
id = LAST_INSERT_ID(id)
Then you can use mysqli_insert_id() regardless of if it was an UPDATE or INSERT
For example, if I run (with a record of id=2 exists; so we'll update);
INSERT INTO foobar (id, foo) VALUES (2, 'bar') ON DUPLICATE KEY UPDATE foo = 'baz', id = LAST_INSERT_ID(id);
SELECT LAST_INSERT_ID();
The output is 2, as that was the last insert id.

Categories