Wanting to get some clarity for the below code, I have made comments next to each line and question marks where I am need some assistance please
$sql = 'SELECT * FROM users'; // Select all data
$query = $this -> conn -> prepare($sql); // Connects to server and executes select all query
$query -> execute(array(':email' => $email)); // ????
$data = $query -> fetchObject(); // Stores the results on the executed query in $data??
$email substitutes your ':email' with $email variable.
See examples here
In your case, since you don't have any parameter marker, you can directly execute the query without any parameter binding.
$sql = 'SELECT * FROM users';
$query = $this -> conn -> prepare($sql);
$query -> execute();
$data = $query -> fetchObject();
The ':email' => $email portion is binding whatever $email is to the :email param in the sql statement. As your SQL statement doesn't have an :email portion, this isn't doing anything.
This example shows how it could possibly be used:
$email = 'myEmail#aol.com';
$sql = 'SELECT * FROM users where email = :email';
$query = $this->conn->prepare($sql);
$query->execute(array(':email' => $email));
$data = $query->fetchObject();
execute is fetching the sql.
:email => $email this is binding email to $email variable.
btw, u got no email param, why u need bindparam?? u need to bind when u write some sql like
SELECT * FROM users where email = :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;
}
Here I want to add another variable using AND.
$query = $db->prepare("SELECT *
FROM messages WHERE Subject_Code = ' ".$_SESSION['sub1']." ' ");
I want to add Week = ' ".$_SESSION["weekS1"]." ' to this query using AND. How can I do it?
PHP PDO supports positional (?) and named (:email) placeholders, the latter always begins from a colon and can be written using letters, digits and underscores only. Also note that no quotes have to be ever used around placeholders.
Eg:
The following becomes
$sql = "SELECT * FROM users WHERE email = '$email' AND status='$status'";
To
$sql = 'SELECT * FROM users WHERE email = ? AND status=?';
OR
$sql = 'SELECT * FROM users WHERE email = :email AND status=:status';
With placeholders, you have to prepare it, using the PDO::prepare() method
To get the query executed, you must run execute() method of this object, passing variables in it, in the form of array
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ? AND status=?');
$stmt->execute([$email, $status]);
$user = $stmt->fetch();
// or
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email AND status=:status');
$stmt->execute(['email' => $email, 'status' => $status]);
$user = $stmt->fetch();
Very Good Reference for full tutorial : https://phpdelusions.net/pdo
If you are using PHP5+, You are supposed to bind your parameters outside of the query string when executing your statement.
Example:
$query = $db->prepare('SELECT * FROM messages WHERE Subject_Code = :subj AND Week = :week')
$query->execute(array(
':subj' => $_SESSION['sub1'],
':week' => $_SESSION["weekS1"],
));
When I want to find a value from a row using PDO I use the following method:
//Search whether user exists
$sqlQueryEmailLogin = $dbh->prepare("SELECT vendor_id, first_name, last_name, email_login, user_password, passport_id, login_attempts, login_last_attempt FROM $tableVendorDetails WHERE email_login = ?");
$sqlQueryEmailLogin->bindValue(1, $emailLogin);
$sqlQueryEmailLogin->execute();
and the following PHP code for the search field
$emailLogin = 'xyz#abc.com'
Now I'd like to search two columns or more and use the following code
$sql = "SELECT * FROM articles WHERE id = ? AND status = ?";
$stmt = $conn->prepare($sql);
$stmt->bindValue(1, $id);
$stmt->bindValue(2, $status);
$stmt->execute();
I'd like to search the two columns from a string. How should I go about it, please?
The string value i go is from a html form with one input box
I'd like a string that is capable of searching two values from a MySQL table e.g.
$search = $id; and
$seach = $status;
in this case both cancel each other
You could simplify it by using the method described by #gbestard. But you should also do this:
$search = 'asdf'; // fill this with your form input
$sql = "SELECT * FROM articles WHERE id = :id OR status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(
':id' => $search,
':status' => $search,
));
Notice the change to OR in the query, and supplying the $search multiple times...
That's what I'm using
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->execute(array(':id' => $id , ':status' => $status));
Try the following
$sql = "SELECT * FROM articles WHERE id = :id AND status = :status";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':id', $id);
$stmt->bindValue(':status', $status);
$stmt->execute();
See docs http://php.net/manual/en/pdostatement.bindvalue.php
You should use OR instead of AND. That way, you will get all rows that match either by id or by status.
SELECT * FROM articles WHERE id = ? OR status = ?
This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I currently have a Get varible
$name = $_GET['user'];
and I am trying to add it to my sql statement like so:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
and run
$result = $pdo -> query($sql);
I get an invalid column name. But that doesn't make sense because if I manually put the request like so
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
I get the column data, just not when I enter it as a get variable. What am I doing wrong. I am relatively new to pdo.
Update:
Now I have the following:
$name = $_GET['user'];
and
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
but I am getting
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ':name' at line
> 1
For your query with the variable to work like the one without the variable, you need to put quotes around the variable, so change your query to this:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
However, this is vulnerable to SQL injection, so what you really want is to use a placeholder, like this:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
And then prepare it as you have:
$result = $pdo->prepare( $sql );
Next, bind the parameter:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
And lastly, execute it:
$result->execute();
I find this best for my taste while preventing SQL injection:
Edit: As pointed out by #YourCommonSense you should use a safe connection as per these guidelines
// $conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = 'SELECT * FROM uc_users WHERE user_name = ?';
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
// perhaps you'll need these as well
$count = $result->num_rows;
$row = $result->fetch_assoc();
/* you can also use it for multiple rows results like this
while ($row = $result->fetch_assoc()) {
// code here...
} */
BTW, if you had more parameters e.g.
$sql = 'SELECT * FROM table WHERE id_user = ? AND date = ? AND location = ?'
where first ? is integer and second ? and third ? are string/date/... you would bind them with
$stmt->bind_param('iss', $id_user, $date, $location);
/*
* i - corresponding variable has type integer
* d - corresponding variable has type double
* s - corresponding variable has type string
* b - corresponding variable is a blob and will be sent in packets
*/
Source: php.net
EDIT:
Beware! You cannot concatenate $variables inside bind_param
Instead you concatenate before:
$full_name = $family_name . ' ' . $given_name;
$stmt->bind_param('s', $full_name);
Try this .You didn't put sigle quote against variable.
$sql = "SELECT * FROM uc_users WHERE user_name = '". $name."'";
Note: Try to use Binding method.This is not valid way of fetching data.
$sql = "SELECT * FROM 'uc_users' WHERE user_name = '". $name."' ";