I have a PostgreSQL query to insert data into my table but for some reason, It's not inserting the data into the table
When I var_dump the execute statement if returning false.
foreach($information as $data){
$name = $data['name'];
$id = $data['id'];
$time = $data['time'];
$query = "INSERT INTO students(name,id,time)"
."VALUES('$name','$id','time')";
//prepare and execute
$stmt = $psql->prepare($query);
$result = $stmt->execute();
var_dump($result);
}
Most probably '$name' is not being understood in the query. Also, you should check for the existence of those variables
Try doing something like this
if (isset($name, $id, $time)) {
$query =
'DO$$
BEGIN
IF NOT EXISTS(select 1 from students where name = \'$name\')
THEN
INSERT INTO student("name", "id", "time")
VALUES (\'$name\', \'$id\', \'$time\')
END IF;
END;
$$;'
}
Related
I've created an UPDATE statement that updates only if the string's length is greater than 0.
I'm trying to escape quotes within my UPDATE statement once the condition is met. I've been using addslashes($name), but with this new condition addslashes no longer works.
Previous:
$mysqli->query("UPDATE table SET name='".addslashes($name)."' WHERE id=1") or die($mysqli->error);
Current:
$mysqli->query("UPDATE table SET name=IF(LENGTH($name)=0, name, '$name') WHERE id=1") or die($mysqli->error);
Where do I place addslashes() for this function to correctly escape characters? Will this function even work within this particular MySQL statement for PHP?
The problem with your second query is that $name inside the call to LENGTH needs to be in quotes too i.e.
$mysqli->query("UPDATE table SET name=IF(LENGTH('$name')=0, name, '$name') WHERE id=1") or die($mysqli->error);
To use addslashes in that query, you would write:
$mysqli->query("UPDATE table SET name=IF(LENGTH('".addslashes($name)."')=0, name, '".addslashes($name)."') WHERE id=1") or die($mysqli->error);
But really you should consider using a prepared statement instead; then you won't have to worry about escaping quotes. Additionally, you should check the length of $name in PHP and not run the query at all if it is empty. Something like this should work (I'm assuming you have a variable called $id which stores the id value for the update).
if (strlen($name)) {
$stmt = $mysqli->prepare("UPDATE table SET name=? WHERE id=?");
$stmt->bind_param('si', $name, $id);
$stmt->execute() or die($stmt->error);
}
If you have multiple pieces of data to update, you could try something like this:
$name = 'fred';
$city = '';
$state = 'SA';
$id = 4;
$params = array();
foreach (array('name','city','state') as $param) {
if (strlen($$param)) $params[$param] = $$param;
}
$sql = "UPDATE table SET " . implode(' = ?, ', array_keys($params)) . " = ? WHERE id = ?";
$types = str_repeat('s', count($params)) . 'i';
$params['id'] = $id;
$stmt = $mysqli->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute() or die($stmt->error);
I try to translate this query to my PDO object from this thread:
UPDATE table_name
SET col1 = <<new value>>,
col2 = <<new values>>,
last_modified_timestamp = <<new timestamp>>
WHERE primary_key = <<key column>>
AND last_modified_timestamp = <<last modified timestamp you originally queried>>
So i have a "modified" field in the mysql table and fetch the data (SELECT modified AS last_modified) to pre-fill in a hidden field in my form and post the value to the object:
$position->readOne();
$position->last_modified = $_POST['last_modified'];
<input name='last_modified' value='{$position->last_modified}'>
My object update query looks like:
UPDATE positions
SET
... some values ...
WHERE id=:id
AND modified=:last_modified
$stmt->bindParam(":last_modified", $this->last_modified);
If I check the posted variables, everything looks fine but the update query ignores my second where clause completely and override the modified field after post the form.
Sure a beginner issue but I canĀ“t find it.
Thanks
EDIT:
Select query
public function readOne(){
$query = "SELECT
p.position,
p.modified,
p.modified AS last_modified
FROM positions p
WHERE id = ?
LIMIT 0,1";
$stmt = $this->conn->prepare( $query );
$stmt->bindParam(1, $this->id);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$this->position = $row['position'];
$this->modified = $row['modified'];
$this->last_modified = $row['last_modified'];
}
Update query
public function updatePosition(){
$this->getTimestamp();
$query = "UPDATE positions
SET
position=:position,
modified=:modified,
WHERE id=:id
AND modified=:last_modified";
$stmt = $this->conn->prepare($query);
$this->position=htmlspecialchars(strip_tags($this->position));
$stmt->bindParam(":id", $this->id);
$stmt->bindParam(":position", $this->position);
$stmt->bindParam(":modified", $this->timestamp);
$stmt->bindParam(":last_modified", $this->last_modified);
if($stmt->execute()){
print_r($this->last_modified);
return true;
}
print_r($stmt->errorInfo());
return false;
}
public function getTimestamp(){
date_default_timezone_set('Europe/Berlin');
$this->timestamp = date('Y-m-d H:i:s');
}
I figured it out. The update query and everything else worked fine but the problem was the notification handling, so the function updatePosition() told me everything was updated but it worked as it should and it did not update anything if the value was not the same.
This fixed it:
if($stmt->execute()){
$affected_rows = $stmt->rowCount();
if ($affected_rows == 1) {
return true;
}
This helped me to understand how it works ... PDOStatement::execute() returns true but the data is not updated
I have a script which is containing some queries:
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
As you see there is two statements (insert and update). All I'm trying to do is making sure both of them work or none of them.
I mean I want to implement a dependency between those two statements. If updating fails, then inserting shouldn't work and vice versa. How can I do that?
You could use sql transactions
http://www.sqlteam.com/article/introduction-to-transactions
You can use transactions and PDO has an api for this (http://php.net/manual/en/pdo.begintransaction.php),
$id = $_GET['id'];
$value = $_GET['val'];
// database connection here
try{
$db_conn->beginTransaction();
// inserting
$stm1 = $db_conn->prepare("INSERT into table1 (col) VALUES (?)");
$stm1->execute(array($value));
// updating
$stm2 = $db_conn->prepare("UPDATE table2 SET col = "a new row inserted" WHERE id = ?");
$stm2->execute(array($id));
$db_conn->commit();
}
catch(PDOException $e){
$db_conn->rollBack();
}
As others said, you could use 'transactions'.
Or
you could mannualy check whether the data is right in the database. Just 'select' what you have inserted.
The 'execute' function return 'true' on success or 'false' on failure. You can do something like:
$isDone=$stm1->execute(array($value));
if(!$isDone){
echo 'Operation fails, I will stop.';
return false;
}
please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}
I want to insert number of records using following script. But, only the first one gets inserted. After that, it just stops without showing any error. What is wrong with these prepared statement execution?
//$dbc = database connection //shortan here
// $mid[] = {1,2,3,4}; //sortened here.
$q5 = "INSERT INTO user_book_trn(user_id, member_id, book_id, date_read, lang_id) VALUES (?, ?, ?, now(), ?)";
$s5 = mysqli_prepare($dbc, $q5);
//Bind the variables:
mysqli_stmt_bind_param($s5, 'iiii', $user_id, $member_id, $book_id, $lang_id);
foreach($mid as $mk => $mv) { //check for each selected check box value from member list:
$q2 = "SELECT user_id, member_id, book_id FROM user_book_trn WHERE user_id = {$_SESSION['myuser']['userid']} and member_id = {$mv} and book_id= {$w}";
$r3 = mysqli_query($dbc, $q2);
if (mysqli_num_rows($r3) == 0) { //title is available for this user.
//Assign the values to variables:
$user_id = (int)$_SESSION['myuser']['userid'];
$member_id = (int)$mv;
$book_id = (int)$w;
$lang_id = (int)$_SESSION['lid'];
//just to check each iteration gets new values:
echo "user_id : $user_id \n";
echo "member_id : $member_id \n";
echo "book_id : $book_id \n";
//Execute the query:
mysqli_stmt_execute($s5);
if (mysqli_affected_rows($dbc) == 1) {
//this runs ok just for the first iteration.. Why?
echo "<p><b> The book $t is added. </b></p>";
$_SESSION['bookid'] = $book_id;
}
}
}
Don't know the exact details, but as far as I know the prepared statement is bound to a result set after execution. You need to reset it first
mysqli_stmt_reset($s);
http://php.net/mysqli-stmt.reset
Additional you should consider using useful variable names. And because you mentioned, that you cannot see any error:
mysqli_stmt_error_list($s5);
http://php.net/mysqli-stmt.error-list
http://php.net/mysqli-stmt.errno
http://php.net/mysqli-stmt.error