I'm quite new to php and previously have just been using mysqli for my queries. However I always see people saying to use prepared statements instead, so i went through my project in an effort to change all my queries into prepared statements. This particular query is not updating
$email = $userDetails['email'];
$token = bin2hex(random_bytes(16));
$username = $userDetails['username'];
$timestamp = date('Y/m/d H:i:s');
$sql = "UPDATE users SET token = ? AND timestamp = ? WHERE email = ?";
$stmt = mysqli_prepare($connect, $sql);
mysqli_stmt_bind_param($stmt,"sss",$token,$timestamp,$email);
mysqli_stmt_execute($stmt);
You are using AND instead of , in your UPDATE query :
$sql = "UPDATE users SET token = ?, timestamp = ? WHERE email = ?";
Related
//Positional Params
$emailToken = $_GET['token'];
$sql = 'SELECT * FROM signup WHERE token = ?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$emailToken]);
$message = $stmt->fetchAll();
Basically I have a email token i parse from the url and want to check whether in the database does it exist or not. No matter what it won't valid even though i checked and echo the emailToken is the exact same.
I tested with another variable
$sql = 'SELECT * FROM signup WHERE email = ?';
$stmt->execute(['asd#gmail.com']);
And it works. Any idea?
It might just be personal preference, but I like being more specific with the bind variables and the syntax never seems to fail me.
$emailToken = $_GET['token'];
$sql = 'SELECT * FROM signup WHERE token = :token';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':token', $emailToken, PDO::PARAM_STR);
$stmt->execute();
$message = $stmt->fetchAll();
building a string with the syntax (never keep code like this, it is only a test)
$sql = "SELECT * FROM signup WHERE token = '" . $_GET['token'] . "'";
var_dump( $sql );
$stmt = $pdo->prepare($sql);
$stmt->execute();
$message = $stmt->fetchAll();
then you can test this outputted code in a query tool to make sure it is syntactically correct.
This is my first query, i want to use the multiple itemID's extracted for another query.
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT itemID from mycart where email = '".$email."' ";
$result = $conn->query($querystring);
$rs = $result->fetch_array(MYSQLI_ASSOC);
The second query that need
$query = "SELECT * from CatalogueItems where itemID = '".$itemID."'";
How do i make these 2 query run?
Firstly, Your code is open to SQL injection related attacks. Please learn to use Prepared Statements
Now, from a query point of view, you can rather utilize JOIN to make this into a single query:
SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = $email /* $email is the input filter for email */
PHP code utilizing Prepared Statements of MySQLi library would look as follows:
$conn = new mysqli(server, dbuser, dbpw, db);
$email = $_GET['email'];
$querystring = "SELECT ci.*
FROM CatalogueItems AS ci
JOIN mycart AS mc ON mc.itemID = ci.itemID
WHERE mc.email = ?"; // ? is the placeholder for email input
// Prepare the statement
$stmt = $conn->prepare($querystring);
// Bind the input parameters
$stmt->bind_param('s', $email); // 's' represents string input type for email
// execute the query
$stmt->execute();
// fetch the results
$result = $stmt->get_result();
$rs = $result->fetch_array(MYSQLI_ASSOC);
// Eventually dont forget to close the statement
// Unless you have a similar query to be executed, for eg, inside a loop
$stmt->close();
Refer to the first query as a subquery in the second:
$query = "SELECT * from CatalogueItems WHERE itemID IN ";
$query .= "(" . $querystring . ")";
This is preferable to your current approach, because we only need to make one single trip to the database.
Note that you should ideally be using prepared statements here. So your first query might look like:
$stmt = $conn->prepare("SELECT itemID from mycart where email = ?");
$stmt->bind_param("s", $email);
This creates a variable out of your result
$query = "SELECT itemID FROM mycart WHERE email = :email";
$stm = $conn->prepare($query);
$stm->bindParam(':email', $email, PDO::PARAM_STR, 20);
$stm->execute();
$result = $stm->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $pers) {
$itemID = $pers->itemID;
}
I've got an HTML form into which a user can enter an SQL query.
The query needs to be entered into a field of my MYSql database. But for complex queries that include % _ , ; ' " $ < > etc... it fails.
How would i go about entering this info into the DB without error?
I know the below is not a very secure way to do it, for now, I just need it to work :)
// Get values from form
$username = $_SESSION['user'];
$appname = $_POST['appname'];
$sql2 = $_POST['sql'];
// Insert data into mysql
$sqlquery="INSERT INTO puresql (username,appnm, query)VALUES('$username','$appname', '$sql2')";
$result=mysqli_query($dbconn,$sqlquery);
For anyone else with this issue. the below works, using mysqli_real_escape_string
$date = date("Y/m/d");
echo "$date";
$appname = mysqli_real_escape_string($dbconn, $_POST['appname']);
$sql2 = mysqli_real_escape_string($dbconn, $_POST['sql']);
$username = mysqli_real_escape_string($dbconn, $_SESSION['user']);
// Insert data into mysql
$sqlquery="INSERT INTO livepurespark (username,appnm, query, date)VALUES('$username','$appname', '$sql2', '$date')";
$result=mysqli_query($dbconn,$sqlquery);
Another way of saving complex texts in database fields with added benefit of protection from sql injection is by using parameterized query statements (Prepared Statements).
$username = $_SESSION['user'];
$appname = $_POST['appname'];
$sql2 = $_POST['sql'];
$stmt = mysqli_prepare($dbconn, "INSERT INTO puresql (username,appnm, query)VALUES('?','?','?')");
mysqli_stmt_bind_param($stmt, "sss", $username, $appname, $sql2);
mysqli_stmt_execute($stmt);
bellow is my code.Error shown is like
fatal error: call to undefined function execute() on line 21,
how could i solve this problem?
<?php
include 'config/dbconfig.php';
include 'lib/function.php';
include 'helper/helper.php';
$db = new rootfunc();
$fm = new formate();
if(!empty($_POST['name']) or !empty($_POST['email']) or !empty($_POST['password1']) or !empty($_POST['dob']) or !empty($_POST['gender']) ){
$name = $fm->validation($_POST['name']);
$email = $fm->validation($_POST['email']);
$password = $fm->validation($_POST['password1']);
$dob = $_POST['dob'];
$gender = $fm->validation($_POST['gender']);
$query = $pdo->prepare("SELECT * FROM user_table WHERE name = ? AND email = ?");
$query = execute(array($name,$email));
$numRow = $query->rowCount();
if(!$numRow){
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
$query->execute(array($name,$email,$password,$dob,$gender));
echo "Congrates, please login..";
}else{
echo "name and email exist..";
}
}
?>
In both cases you are overwriting $query:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$query = $pdo->prepare($query);
You need to give the execution a different variable to hold the object, for example:
$query = "INSERT INTO user_table (name,email,password,dob,gender) VALUES (?,?,?,?,?)";
$result = $pdo->prepare($query);
$result->execute(array($name,$email,$password,$dob,$gender));
In addition you should allow users to use the passwords / phrases they desire. Don't limit passwords.
While you're working with passwords never store them as plain text! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure that you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.
I also noticed this in your code
$numRow = $query->rowCount();
Since the query is a SELECT query it will not work with rowCount()
From the docs:
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
For SELECT when you are not doing a COUNT() query you can return the number of rows like this after you execute the query;
$rows = $result->fetchAll();
$num_rows = count($rows);
In your case it is not necessary to check the count though - just check to make sure the query executed which is enough to get into your conditional statements.
I have a strange problem where every time I do a simple DELETE query to delete WHERE email =. For some reason after deletion it also does a new INSERT with the same email? There is no INSERT anywhere and there are no triggers... Does anybody know why this happens? The table has a email and a nr with auto_increment.
$check_email = $_POST['email'];
$query = "SELECT `email` FROM `newsletter` WHERE email = '$check_email';";
$sth = $dbh->prepare($query);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$check_users_email = $row['email'];
if($check_users_email != ''){
$query_update = "DELETE FROM `newsletter` WHERE email = '$check_users_email';";
}
$sth = $dbh->prepare($query_update);
$sth->execute();
Before deletion: email=test#email.com | nr=1
After deletion: email=test#email.com | nr=2
it might be in your sql string, since you're using prepared statements.
in PDO you should use named or unnamed placeholders. then after preparing the query, you pass the prams as an array when you execute the statement.
If you're using PDO, no need to use single quotes. just the column name and for the search value just use placeholders and then pass on the values on execution as an array.
NOTE: i renamed the PDO object $sth inside the 'if' statement, just to avoid name clash. also i moved the last 2 lines inside the 'if' statement, because you need the value of the sql string '$query_update' which will not be available if that statement returned false.
also to check if the variable $check_users_email is empty, you can use empty() or strlen().
try this:
$check_email = $_POST['email'];
$query = "SELECT email FROM newsletter WHERE email = :check_email";
$sth = $dbh->prepare($query);
$sth->execute(array(':check_email' => $check_email));
$row = $sth->fetch(PDO::FETCH_ASSOC);
$check_users_email = $row['email'];
if($check_users_email != ''){
$query_update = "DELETE FROM newsletter WHERE email = :check_users_email";
$sth2 = $dbh->prepare($query_update);
$sth2->execute(array(':check_users_email' => $check_users_email));
}