getting session into each page - php

i want to insert into a table depending on the id of the session:
here the code in class.php:
public function activate($activation, $id,$change,$userID){
$stm1= $this->conn->prepare("INSERT INTO `log` (`date`,`change`) VALUES(CURRENT_TIMESTAMP(),'$change') WHERE `user_id` =$userID");
($stm1->execute());
$stmt = $this->conn->prepare("UPDATE `segments` SET `activation` = '$activation' WHERE `id` = '$id'")
or die($this->conn->error);
if ($stmt->execute()) {
$stmt->close();
$this->conn->close();
return TRUE;
}
}
at the top of the page i have this:
require './config.php';session_start();$userID = $_SESSION['user_id'];
and in action.php where the action go i have this:
$conn = new db_class();
$conn->activate($activation, $id,$change,$userID);
echo "Updated successfully.";
exit;
the first query insert into log is not working \ please help

This should be a comment but I don't have the rep yet...
Primarily, you don't do that type of insert with a WHERE clause. The insert will fail.
As an aside, that insert is open to sql injection. Bind your your parameters. Also, you should add error handling. If you had that, you would see the insert fails. Quick example (1 way...there are other ways...and I assumed $change is a string and $userId is an int...)
$sql = 'INSERT INTO log
SET `date` = CURRENT_TIMESTAMP(),
change = :change,
user_id = :user_id;';
$stmt = $this->conn->prepare( $sql );
$stmt->bindParam( ':change', $change, PDO::PARAM_STR );
$stmt->bindParam( ':user_id', $userID, PDO::PARAM_INT );
$result = $stmt->execute();
if (!$result) {
// failure -> get and handle the error
$error_array = $stmt->errorInfo();
} else {
// do something
}
The docs can help > pdo::execute, pdo::errorinfo

Related

how to update empty value with bind parameters in php mysqli

I am creating message delete script in PHP MYSQLI. I have added zero value to update column. my script is working but I want to add zero value with bind parameters.
Here is my source code
<?php
require_once "config.php";
if (isset($_GET['to_id'])) {
$id = $_GET['to_id'];
$session_id = $_SESSION['userid'];
}
$stmt = $con->prepare("UPDATE pm SET from_delete = '0' WHERE id = ? AND from_id = ?");
$stmt->bind_param("ss", $id, $session_id);
if ($stmt->execute()) {
echo"deleted successfully";
} else {
echo "Failed to delete<br/>";
}
?>
Just add another placeholder ? and bind value to it:
$stmt = $con->prepare("UPDATE pm SET from_delete = ? WHERE id = ? AND from_id = ?");
$zero = '0';
$stmt->bind_param("sss", $zero, $id, $session_id);

No Update done with PDO php

I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}

Multiple MySQLi prepared UPDATE statement in a SELECT

I have two or more statements on one page of my site. And it does not work properly.
The first code is like that:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
echo $gpname;
}
}
$statement->close();
The problem is when I try to add the second code to it:
if($_GET[buy]=='ch'){
$statement = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement->bind_param('s', $gpname);
$results = $statement->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
My code looks like this, but not working:
$query = "SELECT gpname FROM guineapigs WHERE fbid=?";
if ($statement = $mysqli->prepare($query)) {
$statement->bind_param('s', $_SESSION[FBID]);
$statement->execute();
$statement->bind_result($gpname);
while($statement->fetch()) {
if($_GET[buy]=='ch'){
$statement2 = $mysqli->prepare("UPDATE users SET `money` = `money`+ 22000 WHERE gpname=?");
$statement2->bind_param('s', $gpname);
$statement2->execute();
header( "Location: /test.php?bsuccess=ch" );
}
if($_GET[bsuccess]=='ch'){
echo "Successfully added 22000 money..";
}
}
}
$statement->close();
What am I doing wrong? I want to add even more UPDATE querys after selecting.
Ohh, I'm an idiot! That was the mistake:
Instead of
while ($stmt1->fetch()){
};
needs only:
while ($stmt1->fetch());
Here's a working example with some development:
<?php
ob_start();
session_start();
include_once 'dbtest.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$mysqli->autocommit(FALSE); //turn on transactions
$stmt1 = $mysqli->prepare("SELECT fbname,fbemail FROM users WHERE fbid = ?");
$stmt1->bind_param("s", $_SESSION['FBID']);
$stmt1->execute();
$stmt1->bind_result($fbname,$fbemail);
while ($stmt1->fetch());
$stmt2 = $mysqli->prepare("INSERT INTO test (name,email) VALUES (?, ?)");
$stmt2->bind_param("ss", $fbname, $fbemail);
$stmt2->execute();
$stmt2->close();
$stmt1->close();
$mysqli->autocommit(TRUE); //turn off transactions + commit queued queries
} catch(Exception $e) {
$mysqli->rollback(); //remove all queries from queue if error (undo)
error_log($e);
}
?>
Thank you anyway!!

Update an enum type

This is my Code:
public function enUser($userID) {
try {
$userStatus = "Y";
$tokenCode = "";
$sql = ('UPDATE tbl_users SET userStatus = ? AND tokenCode = ? WHERE userID = ?');
$stmt = $this->conn->prepare($sql);
$stmt->bindParam(1, $userStatus);
$stmt->bindParam(2, $tokenCode);
$stmt->bindParam(3, $userID);
$stmt->execute();
} catch (PDOException $e) {
echo $e->getMessage();
}
}
This is my enum in database
I have try more to edit it. But in database always appear nothing. I mean in the field 'userStatus' after running the update script, its just value like "" (empty). Can any one help me? Thanks.
You update must be:
'UPDATE tbl_users SET userStatus = ?, tokenCode = ? WHERE userID = ?
See the comma instead of AND
And make sure that $userID exists in your DB

Using isset for correction?

I'm new to PHP,I got error in my web page.It said:
Notice: Undefined index: itemid in /home/tz005/public_html/COMP1687/edit.php on line 103
Can I use isset to fix this problem? If yes, how to do so? Here is my script:
<?php
//include database connection
include 'dbconnect.php';
// if the form was submitted/posted, update the item
if($_POST){
//write query
$sql = "UPDATE
item_information
SET
itemtitle = ?,
itemdescription = ?,
date = ?,
WHERE
itemid= ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(
'sssi',
$_POST['itemtitle'],
$_POST['itemdescription'],
$_POST['date'],
$_POST['itemid']
);
// execute the update statement
if($stmt->execute()){
echo "Item was updated.";
// close the prepared statement
$stmt->close();
}else{
die("Unable to update.");
}
}
$sql = "SELECT
itemid, itemtitle, itemdescription, date
FROM
item_information
WHERE
id = \"" . $mysqli->real_escape_string($_GET['itemid']) . "\"
LIMIT
0,1";
// execute the sql query
$result = $mysqli->query( $sql );
//get the result
if ($result = $mysqli->query( $sql )) {
if ($row = $result->fetch_assoc()) {
// $row contains data
}
}
//disconnect from database
$result->free();
$mysqli->close();
?>
change
$mysqli->real_escape_string($_GET['itemid'])
to
$mysqli->real_escape_string($_POST['itemid'])
or use empty() or isset() to check values exist
Yes you can do it with isset() function
Create conditions for it
if(isset($_GET['itemid'])){
//execute your code
}
else{
//header them back to page or show error that itemid not set or something else whatever suits you
}

Categories