My current code updates all values, and if there is an empty parameter it updates the corresponding field on the table to null. I want to update only the fields that have a value.
This is my code:
$sql = "
UPDATE drinks SET
name = :name, // Mojito -> Update it
description = :description, // Lorem ipsum.. -> Update it
glass_id = :glass_id, // NULL -> do not update
video_url = :video_url // NULL -> do not update
WHERE id = '$drinkId'
";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':glass_id', $glassId);
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}
you don't want to update those 2 fields when they are empty.
this code check if a field is null and only when it is not null it will add the field to the query, also the same for binding the value.
$sql = 'UPDATE drinks SET';
$sql = sql . 'name = :name,';
$sql = sql . 'description = :description';
if (!is_null($glassId))
$sql = sql . ',glass_id = :glass_id';
if (!is_null($videoUrl))
$sql = sql . ',video_url = :video_url';
$sql = sql . ' WHERE id = :drinkId';
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $drinkName);
$stmt->bindParam(':description', $description);
$stmt->bindParam(':drinkId', $drinkId);
if (!is_null($glassId))
$stmt->bindParam(':glass_id', $glassId);
if (!is_null($videoUrl))
$stmt->bindParam(':video_url', $videoUrl);
$stmt->execute();
// Close databse
$db = null;
} catch(PDOException $e) {
echo $e;
}
Related
I already write the code to check if table call hm2_history type = commission if yes then insert data into table call hm2_deposit, when I test echo was correct and show the result is :
Connected successfully
354
368
But won't insert into hm2_deposit , I don't know how to adjust it i have a little bit knowledge about php
This is my code
<?php
$servername = "localhost";
$username = "tinybaht_findroom";
$password = "212224";
function setChecked($conn,$params){
$s = $conn->prepare("UPDATE `hm2_history`
SET history_ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=tinybaht_findroom", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT * FROM hm2_history");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$a = $stmt->fetchAll();
$plans = array();
foreach($a as $i){
$plans[$i['type']] = 'commissions';
}
$stmt = $conn->prepare("SELECT * FROM hm2_history WHERE id NOT IN(SELECT ref_id FROM hm2_deposits WHERE ref_id > 0) AND type='commissions'");
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$rows = $stmt->fetchAll();
foreach($rows as $k=>$v) {
$plan_type = isset($plans)?:'';
$m = $v['type'];
if (!empty($plan_type)){
echo '<br>'.$v['id'];
if ($m = "commissions" ){
setChecked($conn,array('id'=>$v['id']));
continue;
}
}else{
setChecked($conn,array('id'=>$v['id']));
continue;
}
//deposits
$s = $conn->prepare("INSERT INTO `hm2_deposits`
SET `user_id`=:user_id,
`type_id`=:type_id,
`deposit_date`=:deposit_date,
`last_pay_date`=:last_pay_date,
`status`=:status,
`q_pays`=:q_pays,
`amount`=:amount,
`actual_amount`=:actual_amount,
`ec`=:ec,
`compound`=:compound,
`dde`=:dde,
`unit_amount`=:unit_amount,
`bonus_flag`=:bonus_flag,
`init_amount`=:init_amount,
`ref_id`=:ref_id
");
$v['ref_id'] = $v['id'];
$v['amount'] = $v['amount']*$rate;
$v['actual_amount'] = $v['actual_amount']*$rate;
$v['init_amount'] = $v['init_amount']*$rate;
$v['bonus_flag'] = 1;
$v['type_id']= 9;
unset($v['id']);
$s->execute($v);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
}
?>
this is photo of my db table name is hm2_deposits hm2_deposits
this is photo of my db table name is hm2_history enter image description here
There is an error in your SQL:
$s = $conn->prepare("INSERT INTO hm2_deposits
SET user_id=:user_id,
type_id=:type_id,
deposit_date=:deposit_date,
last_pay_date=:last_pay_date,
status=:status,
q_pays=:q_pays,
amount=:amount,
actual_amount=:actual_amount,
ec=:ec,
compound=:compound,
dde=:dde,
unit_amount=:unit_amount,
bonus_flag=:bonus_flag,
init_amount=:init_amount,
ref_id=:ref_id
");
Read the proper way to do it at:
https://www.w3schools.com/sql/sql_insert.asp
I need some help
Is there a way to make this in PDO? https://stackoverflow.com/a/1899508/6208408
Yes I know I could change to mysql but I use a mssql server and can't use mysql. I tried some things but I'm not as good with PDO as mysql... It's hard to find some good examples of inserting array's into database with PDO. So quickly said I have a PDO based code connected to a mssql webserver.
best regards joep
I tried this before:
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$data = array_merge($mon_barcode, $mon_merk, $mon_type, $mon_inch, $mon_a_date, $mon_a_prijs);
try{
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
$insertData = array();
foreach($_POST['mon_barcode'] as $i => $barcode)
{
$insertData[] = $barcode;
}
if (!empty($insertData))
{
implode(', ', $insertData);
$stmt = $conn->prepare($sql);
$stmt->execute($insertData);
}
}catch(PDOException $e){
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
The code below should fix your problems.
$db_username='';
$db_password='';
$conn = new \PDO("sqlsrv:Server=localhost,1521;Database=testdb", $db_username, $db_password,[]);
//above added per #YourCommonSense's request to provide a complete example to a code fragment
if (isset($_POST['com_id'])) { //was com_id posted?
//id
$com_id = $_POST['com_id'];
//array
$mon_barcode = $_POST['mon_barcode'];
$mon_merk = $_POST['mon_merk'];
$mon_type = $_POST['mon_type'];
$mon_inch = $_POST['mon_inch'];
$mon_a_date = $_POST['mon_a_date'];
$mon_a_prijs = $_POST['mon_a_prijs'];
$sql = "INSERT INTO IA_Monitor (Com_ID, Barcode, Merk, Type, Inch, Aanschaf_dat, Aanschaf_waarde) VALUES (?,?,?,?,?,?,?)";
try {
$stmt = $conn->prepare($sql);
foreach ($mon_barcode as $i => $barcode) {
$stmt->execute([$com_id, $barcode, $mon_merk[$i], $mon_type[$i], $mon_inch[$i], $mon_a_date[$i], $mon_a_prijs[$i]]);
}
} catch (\PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
}
$conn = null;
Hello guys I have been trying to delete a file using php and I want it to delete the main post, reply's and like then update to the author -10 in his/her point.
Here is my code, using PDO:
<?php session_start();
if(isset($_POST['id'])){
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("DELETE FROM code WHERE cid= {$id}");
$stmt = $db_conn->prepare("DELETE FROM comment WHERE id = {$id}");
$stmt = $db_conn->prepare("DELETE FROM likes_map WHERE lid = {$id}");
$stmt = $db_conn->prepare("UPDATE users SET point -1 WHERE username = {$u}");
$stmt->bindParam(':id', $id);
$stmt->bindParam(':cid', $id);
$stmt->bindParam(':lid ', $id);
$stmt->bindParam(':u ', $_SESSION['username']);
$stmt->execute();
echo "deleted"
} catch(PDOException $e) {
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}else{
echo "You are not allow to delete this";
}
?>
Your first problem is that you are preparing more than one query on the same statement handle and therefore loosing the link to that prepared statement when you prepare the next query.
You are also only executing the queries once and not once per statement!
Also your prepared sql statement do not have the parameters set with the correct syntax
It would also be a good idea to run this code inside a transaction, so if any update of the database fails you are not left with just bits of this process comepleted. This assumes the database is an INNODB database and not an MYISAM one, as transactions dont work on MYISAM
<?php
session_start();
if(!isset($_POST['id'])){
echo "You are not allow to delete this";
exit;
}
include($root . 'dbconn.php');
$form = $_POST;
$id = $form['id'];
try {
$db_conn = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USERNAME,DB_PASSWORD);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// start a transaction
$db_conn->beginTransaction();
$d_code = $db_conn->prepare("DELETE FROM code WHERE cid= :id");
$d_code->bindParam(':id', $id);
$d_comment = $db_conn->prepare("DELETE FROM comment WHERE id = :id");
$d_comment->bindParam(':id', $id);
$d_like = $db_conn->prepare("DELETE FROM likes_map WHERE lid = :id");
$d_like->bindParam(':id ', $id);
$u_user = $db_conn->prepare("UPDATE users SET point -1 WHERE username = :u");
$u_user->bindParam(':u ', $_SESSION['username']);
$d_code->execute();
$d_comment->execute();
$d_like->execute();
$u_user->execute();
$db_conn->commit();
echo "deleted";
} catch(PDOException $e) {
$db_conn->rollBack();
echo "Error:" . $e->getMessage();
}
$db_conn = null;
?>
In my query the update statement doesn't work, the error given is:
Number of parameter doesn't match with prepared statement
this is my code:
public function update_resource($resource)
{
$mysqli = new MySQLi(HOST, USERNAME, PASSWORD, DATABASE);
$this->connection_state($mysqli);
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
AND sigla = '$sigla' AND colore = '$colore' AND planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param("ssssi", $descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}
The code go into the Added condition but the query fail, what's the problem?
public function update_resource($resource)
{
$mysqli = new mysqli(HOST, USERNAME, PASSWORD, DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$id = $resource['id'];
$descrizione = $resource['descrizione'];
$sigla = $resource['sigla'];
$colore = $resource['colore'];
$planning = $resource['planning'];
try
{
$query = "UPDATE risorse SET descrizione = '$descrizione'
, sigla = '$sigla', colore = '$colore', planning = '$planning'
WHERE id = '$id' ";
$stmt = $mysqli->prepare($query);
$stmt -> bind_param($descrizione, $sigla, $colore, $planning, $id);
echo $query;
if($stmt->execute())
{
echo "Added!";
}
else
{
echo "Err: " . $stmt->error;
}
}catch(Exception $e){ echo $e->getMessage(); }
}?
Your problem is that you don't have any placeholders in your query.
Refer to manual to see how placeholders should be set.
In general, placeholders are ? which later will be replaced with values, so your query should look like:
$query = "UPDATE risorse SET descrizione = ?
AND sigla = ? AND colore = ? AND planning = ?
WHERE id = ?";
please visit on http://php.net/manual/en/pdostatement.bindparam.php.you got your answer.see Example #1 Execute a prepared statement with named placeholders
I need to make a PHP code that gets data from server, updates it and echos that updated data to user. I am beginner with PHP so I have no idea how to do this. This is the code I have have now.
So how do I change the code to make it update data ?
<?php
include 'config.php';
$ID = $_GET['ID'] ;
$sql = "select * from table where ID = \"$ID\" and condition = false ";
// This is what I need the table to be updated "Update table where where ID = \"$ID\" set condition = true" ;
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->query($sql);
$data = $stmt->fetchAll(PDO::FETCH_OBJ);
$dbh = null;
echo '{"key":'. json_encode($data) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>
one idea is to create a different database connection file consisting of a pdo connection and reuse it in your application. on how to do that.
in database.php you can do it like
try {
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
//catch the exception here and do whatever you like to.
}
and everywhere you want to use the connection you can do
require_once 'Database.php';
and some of the sample CRUD (Create, Read, Update, Delete) using PDO are.
//Create or Insert
$sth = $dbh->prepare("INSERT INTO folks ( first_name ) values ( 'Cathy' )");
$sth->execute();
//Read or Select
$sth = $dbh->query('SELECT name, addr, city from folks');
//Update
$sth = $dbh->prepare("UPDATE tablename SET col = val WHERE key = :value");
$sth->bindParam(':value', $value);
$sth->execute();
//Delete
$dbh->query('DELETE FROM folks WHERE id = 1');
you should also study about named and unnamed placeholders, to escape SQL injections etc. you can read more about PDO with a very easy to understand tutorial by nettuts here
hope this helps you.
Try this. I think it is along the lines of what you are looking for:
$query = "select * from table where ID = \"$ID\" and condition = false ";
$query_result = #mysql_query($query);
$query_row = mysql_fetch_assoc($query_result);
$update_query = "UPDATE table SET condition = true WHERE ID = {$row['ID']};";
if( #mysql_query($update_query) ) {
echo "Update succeeded!";
} else {
echo "Update failed!";
}
<?php
$ID = 1;
try {
$db = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$select_statement = $db->prepare('select * from table1 where id = :id and `condition` = false');
$update_statement = $db->prepare('update table1 set `condition` = true where id = :id');
$select_statement->execute(array(':id' => $ID));
$results = $select_statement->fetchAll();
$update_statement->execute(array(':id' => $ID));
echo '{"key":' . json_encode($results) .'}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
?>