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() .'}}';
}
?>
Related
Function getUsers_Test() can retrieve data with the limit of 10 rows only while my getUsers_Orig() cannot retrieve any records **my record in the database is almost 50 rows*. No error, no warning. (PHP version 5.5.12)
function getUsers_Test(){
$sql = "SELECT TOP 10 a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function getUsers_Orig(){
$sql = "SELECT a.user_name, a.user_level, a.user_status, b.* FROM user_access a, user_details b WHERE a.emp_code = b.emp_code ORDER BY a.id DESC";
try{
$data = array();
$db = null;
$db = connectDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll();
}catch(PDOException $e){
$data['message'] = "Error: " . $e;
}
echo json_encode($data);
}
function connectDB() {
$dbuser = "myusername";
$dbpass = "mypassword";
$dbh = new PDO('odbc:databaseName', $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
You could try catching a general exception instead of the PDOException
try
{
// ...
} catch (\Exception $e) {
// ...
}
The size of data is not a problem here, the data I was fetching has a special character (A‘ for Ñ). I use to add charset UTF-8 in my connection but still, I wasn't able to fetch it.
This problem occurs when I perform Generate Script and extract data from MSSQL instead of Backup and Restore. So when I execute the script from the Generate Script feature of MSSQL, the character changed and I didn't notice it.
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 wrote some code to check database table name is hms_history if type = commission then will add another row of data into hms_history but change amount_balance to -amount_balance then will add another data to table hms_deposit. I try to write the code but when I check it show only connect successful, but nothing changes in the database at all.
This is my code
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
function setChecked($conn,$params) {
$s = $conn->prepare("UPDATE `hm2_history`
SET ref_id=-1
WHERE id=:id
");
$s->execute($params);
}
try {
$conn = new PDO("mysql:host=$servername;dbname=xxxx", $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
WHERE id NOT IN(SELECT ref_id FROM hm2_history WHERE ref_id > 0) AND
ref_id=0 AND commission=0");
//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['type_id']= 9;
unset($v['id']);
$lastDepositId = $conn->lastInsertId();
$date = date('Y-m-d H:i:s');
$s->execute($v);
//history1
$s = $conn->prepare("INSERT INTO `hm2_history`
SET `user_id`=:user_id,
`amount`=:amount,
`type`=:type,
`description`=:description,
`actual_amount`=:actual_amount,
`date`=:date,
`ec`=:ec,
`deposit_id`=:deposit_id,
`rate`=:rate
");
$x = array(
'user_id'=>$v['user_id'],
'type'=>'bonus',
'amount'=>$v['amount'],
'description'=>'Bonus note',
'actual_amount'=>$v['actual_amount'],
'date'=>$date,
'ec'=>68,
'deposit_id'=>0,
'rate'=>1.0,
);
$s->execute($x);
//history2
$s = $conn->prepare("INSERT INTO `hm2_history`
SET `user_id`=:user_id,
`amount`=:amount,
`type`=:type,
`description`=:description,
`actual_amount`=:actual_amount,
`date`=:date,
`ec`=:ec,
`deposit_id`=:deposit_id,
`rate`=:rate
");
$x = array(
'user_id'=>$v['user_id'],
'type'=>'depoit',
'amount'=> -$v['amount'],
'description'=>'Deposit from plan',
'actual_amount'=> -$v['actual_amount'],
'date'=>$date,
'ec'=>999,
'deposit_id'=>$lastDepositId,
'rate'=>1.0,
);
$s->execute($x);
?>
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;
?>
The below one is the code i'm using for incrementing,it shows no error but the "like" column is not incrementing.
<?php
$id=$_GET['id'];
echo $id;
$dsn = 'mysql:host=127.0.0.1;dbname=as1';
$user = 'root';
$password = '';
try{
// Connect and create the PDO object
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo 'Database connection failed - ';
echo $e->getMessage();
exit;
}
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=:id";
$q=$pdo->prepare($sql);
$q->execute(array($id));
header("Location:upload.php");
}
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=':id'";
$sql="UPDATE photo SET likes = likes + 1 WHERE imagename=:id";
$q=$pdo->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_INT);
$q->execute();
++ known from programming languages does not work with normal SQL syntax.