I need help on converting mysql_query to PDO. The MySQL database is not updating when I edit columns. I've tried translating the following code:
<?php
include("connect.php");
if($_GET['id'] and $_GET['data'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
if(mysql_query("update information set $key='$data' where id='$id'"))
echo 'success';
}
}
?>
Into this:
<?php
include("connect.php");
if(isset($_GET))
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
}
try {
$pdo = new PDO( DSN, DB_USR, DB_PWD );
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->query( "SET NAMES utf8" );
$stmt = $pdo->prepare(
"UPDATE information
SET
key=:data where id=:id"
);
$stmt->bindValue( ':id', $id, PDO::PARAM_INT );
$stmt->bindValue( ':key', $data, PDO::PARAM_STR );
$stmt->execute();
} catch (PDOException $e){
var_dump($e->getMessage());
}
$pdo = null;
You used :key in your bindValue() call when it should be :data. You also need to put $key into the query (you can't use a placeholder for a column name, so this requires variable substitution).
$stmt = $pdo->prepare(
"UPDATE information
SET
$key = :data where id=:id"
);
$stmt->bindValue( ':id', $id, PDO::PARAM_INT );
$stmt->bindValue( ':data', $data, PDO::PARAM_STR );
$stmt->execute();
You should validate $key before substituting it, to prevent SQL injection. Something like:
$allowed_keys = array('col1', 'col2', 'col3');
if (!in_array($key, $allowed_keys)) {
die("Bad key $key");
}
Related
I am using PHP PDO prepared statements. I am passing in a string and returning the record from MYSQL. I am passing three variables to the method.
The query returns nothing. If I perform the same query in phpmyadmin it returns all the correct data. I believe it is the ampersand(&) in the $team variable but, don't know I to work around it. I am not using a link and it is not a form element. It is a straight call to the method.
The values of the three parameters are
$season = '2018-19';
$league = 20;
$team = "Texas A&M University-Kingsville";
Here is my method:
public static function getTeamGames($season, $league, $team){
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season &&
league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $team, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
$weeklyGames = Game::getTeamGames( $season, $league, $tName );
I really appreciate the help of everyone.
Thank you in advance.
I was able to fix the issue.
I had to use html_entity_decode on the $team parameter.
I changed my method to the following:
public static function getTeamGames($season, $league, $team){
$dTeam = html_entity_decode($team);
$conn = parent::connect();
$sql = "SELECT * FROM rfw_games WHERE season = :season && league = :league && home = :team";
try {
$st = $conn->prepare( $sql );
$st->bindValue( ":season", $season, PDO::PARAM_STR );
$st->bindValue( ":team", $dTeam, PDO::PARAM_STR );
$st->bindValue( ":league", $league, PDO::PARAM_INT );
$st->execute();
$games = array();
foreach ( $st->fetchAll() as $row ) {
$games[] = new Game( $row );
}
parent::disconnect( $conn);
return $games;
} catch (PDOException $e ) {
parent::disconnect( $conn );
die( "Query failed: " . $e->getMessage() );
}
}
There is my code of EDIT.php DB_Functions,and g.php..I'm not geting where is the fault is anyone here who can help me to find out mistake on my code
Every things happen as easy but change in table is not reflecting..my SQL query is working properly on XAMP server..
It may be silly mistake but not able to find it..
edit.php
<?php
//error_reporting(0);
include("class_db.php");
include_once('DB_Functions.php');
if (isset ($_GET['edit_id']))
{
$id=$_GET['edit_id'];
{
if(isset($_POST['nam']))
{
$id =($_POST['edit_id']);
$name=($_POST['name']);
$lastname=($_POST['lastname']);
$email=($_POST['email']);
$duser=($_POST['duser']);
$pass=($_POST['pass']);
$mob=($_POST['mob']);
$website=($_POST['website']);
$result = file_get_contents('http://localhost/rajju/demo/webservises/webservises/webservices/g.php?action=update_details&id='.$id.'&name='.$name.'&lastname='.$lastname.'&email='.$email.'&duser='.$duser.'&pass='.$pass.'&mob='.$mob.'&website='.$website);
$result = json_decode($result, true);
if($result == 'success'){
header("location:http://localhost/rajju/demo/webservises/webservises/webservices/list.php");
}
else{
print_r($result);
}
}
}
}
$select =mysql_query("select * from users where id=$id");
$var = mysql_fetch_object($select);
?>
DB_Functions.php
public function updateUser($id,$name,$lastname,$email,$duser,$pass,$mob,$website)
{
$app_list =mysql_query("UPDATE users SET name='".$name."',lastname='".$lastname."',email='".$email."',duser='".$duser."',pass='".$pass."',mob='".$mob."',website='".$website."' WHERE id='".$id."'");
if ($app_list) {
return true;
} else {
return false;
}
}
g.php
else if($tag == 'update_details')
{
$db = new DB_Functions();
//$id = ($_GET['id']);
$name=($_GET['name']);
$lastname=($_GET['lastname']);
$email=($_GET['email']);
$duser=($_GET['duser']);
$pass=($_GET['pass']);
$mob=($_GET['mob']);
$website=($_GET['website']);
//exit (json_encode($name));
if ($db ->updateUser($name,$lastname,$email,$duser,$pass,$mob,$website))
{
exit (json_encode('success'));
}else
{
exit (json_encode('errorzz'));
}
}
The following should work. Note this still wont totally protect you against xss and other attacks. However its a lot better than using mysql_query!! Additionally, you should sanatise and check your incoming $_GET params and Salt+Hash your passwords.
<?php
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE users SET name=:name, lastname=:lastname, email=:email, duser=:duser, pass=:pass, mob=:mob, website=:website, WHERE id=:id";;
$st = $conn->prepare( $sql );
$st->bindValue(":name", $name, PDO::PARAM_STR);
$st->bindValue(":lastname", $lastname, PDO::PARAM_STR);
$st->bindValue(":email", $email, PDO::PARAM_STR);
$st->bindValue(":duser", $duser, PDO::PARAM_STR);
$st->bindValue(":pass", $pass, PDO::PARAM_STR);
$st->bindValue(":mob", $mob, PDO::PARAM_STR);
$st->bindValue(":website", $website, PDO::PARAM_STR);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->execute();
?>
i fight with DB, trying to insert true and false values to my table with column boolean, but always getting just error:
Invalid parameter number
tested with:
$value = true
$value = "true"
$value = 1
Can somebody please advise me?
Thanks
EDIT:
full code would looks like:
// adding value to variabile
if (empty($row['vin']))
$vin = 0;
else
$vin = 1;
//calling insert method
$this->insertToTable($model_code, $typ, $kind, $ts, $vin, $smr, $ire, $manufacturer_code);
//full insert method:
public function insertToTable($code, $name, $kind, $ts, $vin, $smr, $ire, $manufacturer_code)
{
try {
$con = new PDO( DB_HOST, DB_USER, DB_PASS );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO r_vehicle_model(code, name, kind, ts, vin, smr, ire, manufacturer_code) VALUES(:code, :name, :kind, :ts, :smr, :ire, :manufacturer_code)";
$stmt = $con->prepare( $sql );
$stmt->bindValue( 'code', $code, PDO::PARAM_STR );
$stmt->bindValue( 'name', $name, PDO::PARAM_STR );
$stmt->bindValue( 'kind', $kind, PDO::PARAM_STR );
$stmt->bindValue( 'ts', $ts, PDO::PARAM_STR );
$stmt->bindValue( 'vin', $vin, PDO::PARAM_STR );
$stmt->bindValue( 'smr', $smr, PDO::PARAM_STR );
$stmt->bindValue( 'ire', $ire, PDO::PARAM_STR );
$stmt->bindValue( 'manufacturer_code', $manufacturer_code, PDO::PARAM_STR );
$stmt->execute();
}
catch( PDOException $e ) {
echo $e->getMessage();
}
}
full error:
SQLSTATE[HY093]: Invalid parameter number: :vin
Forget :vin in insert query. Number of parameter in values is not equal to bindValue
$sql = "INSERT INTO r_vehicle_model(code, name, kind, ts, vin, smr, ire, manufacturer_code) VALUES(:code, :name, :kind, :ts, ,:vin ,:smr, :ire, :manufacturer_code)";
You're currently using PDO::PARAM_STR to specify that all the parameters you're passing are strings.
You should make choose the appropriate type for the field, so for a boolean consider using PDO::PARAM_BOOL
http://php.net/manual/en/pdo.constants.php
Hi I want to know how can I expire an activation link after 2 days sent tru email for my users who doesn't have their accounts activated yet.. My idea was to use COOKIES but I think its not possible to send COOKIES via email.. can I have some tips and other suggestion please? I've been searching for 6 days now...
Here is what I have so far
$con = new PDO("mysql:host=". db_host .";dbname=".db_name.'', db_username , db_password);
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$c = $_GET['c'];
if($c == 1){
$imputText = $_GET['v'];
$imputKey = "3173aLASOf";
$blockSize = 128;
$mode ="M_CBC";
$es = new ES($imputText, $imputKey, $blockSize,$mode);
$dec=$es->decrypt();
$sql = "SELECT vtokn FROM tmp_user WHERE vtokn = :token LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "token", $dec, PDO::PARAM_STR );
$stmt->execute();
$sqlups = "UPDATE tmp_user SET conf = :c WHERE vtokn = :token AND conf= 0 LIMIT 1";
$stmtups = $con->prepare( $sqlups );
$stmtups->bindValue( "c", $_GET['c'], PDO::PARAM_STR );
$stmtups->bindValue( "token", $dec, PDO::PARAM_STR );
$stmtups->execute();
$result = $stmt->fetchColumn();
$sqltmps = "SELECT tmstamp FROM tmp_user WHERE vtokn = :token LIMIT 1";
$stmttmps = $con->prepare( $sqltmps );
$stmttmps->bindValue( "token", $dec, PDO::PARAM_STR );
$stmttmps->execute();
$result2 = $stmttmps->fetchColumn();
$tme =time()+60*2;
setcookie('exp','d',$result2);
if(isset($_COOKIE['exp']) ){
if($result === $dec){
$sqltb = "SELECT * FROM tmp_user WHERE vtokn = :token LIMIT 1";
$stmttb = $con->prepare( $sqltb );
$stmttb->bindValue( "token", $dec, PDO::PARAM_STR );
$stmttb->execute();
foreach ($stmttb->fetchAll() as $rows) {
$user=$rows['username'];
$password=$rows['password'];
$firstname=$rows['firstname'];
$lastname=$rows['lastname'];
}
$sql2 = "INSERT INTO ofcl_users(email,password,acct_stat) VALUES( :username,:password,1 )";
$stmt2 = $con->prepare( $sql2 );
$stmt2->bindValue( "username", $user, PDO::PARAM_STR );
$stmt2->bindValue( "password", $password, PDO::PARAM_STR );
$stmt2->execute();
echo $user." "."Is Now Activated<br/>" . "<a href='login.php'>Login Now</a>";
$sqldel = "DELETE FROM tmp_user WHERE vtokn = :token AND conf= :c LIMIT 1";
$stmtdel = $con->prepare( $sqldel );
$stmtdel->bindValue( "c", $_GET['c'], PDO::PARAM_STR );
$stmtdel->bindValue( "token", $dec, PDO::PARAM_STR );
$stmtdel->execute();
}else
{
echo "Account was already activated" . $dec;
}
} else {
echo $_GET['t']."Token Expired" . $tme;
}
}
else
{
echo "Invalid Token Reference: " . $dec;
}
This script will run as soon as my link tru email was click the validation if its a link that is a 2 or 3 days old.. Is this correct?
Make use of Timestamp.
When Inserting a Token, make another field in database, say token_timestamp and use time() function for its value.
Then, at the time of Validating Activation Link, make a check something like this:
$current_time = time();
$max_time = 2*24*60*60; // Time in seconds
if (($current_time - $token_timestamp) > $max_time) {
echo "Link Expired!";
}
else {
// Do your Process for Activation here
}
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() .'}}';
}
?>