I am am following a tutorial for MVC and I am stuck in a position where I can't go further.
The problem is that when I am executing the SQL Statement, I am trying to get the value and just print it/echo it.
I have a function where I am achieving it. Here's the code for it :
NOTE : I am using filter_input() method to get the $_POST(['login']) and $_POST(['password']). For some reason, I can't directly use $_POST() method because it giving me a warning for don't access superglobal $_POST directly.
I am not sure what exactly is the issue here. I am getting zero for this and I actually have one entry in the database.
public function run(){
$login = filter_input(INPUT_POST, 'login');
$password = filter_input(INPUT_POST, 'password');
$sth = $this->db->prepare("SELECT id FROM users WHERE
login = :login AND password = MD5(:password)");
$sth->execute(array(
':login' => $login,
':password' => $password
));
$data = $sth->fetchAll();
print_r($data);
/*$count = $sth->rowCount();
print_r($count);
if($count>0){
echo 'Have a record.';
}else{
echo 'No Record found.';
}*/
}
If someone can help me find the issue, I will really appreciate it.
Straight from manual,
PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
After update: Try below,
$sth = $this->db->prepare("SELECT id FROM users WHERE
login = :login AND password = :password");
$sth->execute(array(
':login' => $login,
':password' => md5($password)
));
$data = $sth->fetchAll();
Related
I am trying to write a function that is supposed to receive any MySQL statement and apply it,
The basic idea is not to repeat needed code to write to Database, well what is needed to connect to Database is creating new PDO object, starting a transaction and preparing a statement, binding values to it, executing it,
so every time I want to access the Database I don't have to repeat these steps,
Here is a function that does that :
==============================================================================================
protected function applyQuery($statement, $bindparameters , &$values , $selectStatement, &$result){
try{
$dbh = DataBase::setConnection();// new PDO("MySQL= .....");
$dbh->beginTransaction();
$stmt = $dbh->prepare($statement);
if($bindparameters == true){
foreach($values as $key => $value){
$stmt->bindValue($key, $value);
}
}
$stmt->execute();
$dbh->commit();
if($selectStatement == TRUE){
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
}catch (PDOException $e){
$dbh->rollBack();
throw DataBase::$Errors[0];
}
}
============================================================================================
$statement = the desired statement (e.g 'SELECT * from users WHERE username = :username')
$bindparameters = do we need to bind values (in this examples yes) so its value TRUE
&$values = array by reference in this case equals = (':username' => 'User');
$selectStatement = tells if using SELECT in statement ,in this case TRUE
$result = array by reference in this case the final fetch result will be stored in it
so in this example we get the following call to the function :
applyQuery('SELECT * from users WHERE username = :username', TRUE ,
array(':username' => 'User') , TRUE , result )
My question is : will this code work ? is the logical sequence of what it does and should do make sense ? whats the difference between $stmt->execute and $dbh->commit ? is omitting any line will cause failure to achieve the desired result
Please understand that I did lookup what is PDO and read a lot but unable to answer these questions!
I have been trying to convert a old mysql too pdo as I am trying to learn how pdo works, I have been working on this one file for hours now busting my head and can not figure out what is wrong, and I'm sure its a lot.
try{
$check_user_data = $dbh->query("SELECT * FROM members WHERE username = '$username'");
$stmt = $dbh->prepare($check_user_data);
$stmt->execute();
$result->bind_result($username);
$data_exists = ($check_user_data->fetchColumn() > 0) ? true : false;
if($data_exists = false){
$final_report.="This username does not exist..";
}else{
$get_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
if($get_user_data['password'] == $password){
$start_idsess = $_SESSION['username'] = "".$get_user_data['username']."";
$start_passsess = $_SESSION['password'] = "".$get_user_data['password']."";
$final_report.="You are about to be logged in, please wait a few moments.. <meta http-equiv='Refresh' content='2; URL=members.php'/>";
}
}
foreach ($dbh->query($sql) as $row){
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
Also getting a fatal
Fatal error: Call to a member function execute() on a non-object
Not sure if the fatal is related to the warning or not.
First, change these two lines:
$check_user_data = $dbh->query("SELECT * FROM members WHERE username = '$username'");
$stmt = $dbh->prepare($check_user_data);
to:
$stmt = $dbh->prepare("SELECT * FROM members WHERE username = :username");
$stmt->bindParam(':username', $username);
This makes use of the parameter feature of prepared statements, which prevents SQL injection.
Next, PDO doesn't have a bind_result method, that's part of MySQLI. To get the results, you should do:
$get_user_data = $stmt->fetch(PDO::FETCH_ASSOC);
$data_exists = ($get_user_data !== false);
You should then remove the call to $stmt->fetch in the else block, because it will try to get the next row of results.
The fatal is definitely related to the warning; you are passing the results of $dbh->query() (which is a PDOStatementObject) into $dbh->prepare, causing $dbh->prepare to return something which is not an object.
Just move the SQL into the $dbh->prepare call and get rid of the $dbh->query() entirely.
For people who might come over here my problem was a bit different i was trying to enable a filter on doctrine/symfony project and accidentally made a mistake on the following line :
$filter->setParameter($name, $someObject);
and when i called the function getParameter($name) in addFilterConstraint function i got the same error
Warning: PDO::prepare() expects parameter 1 to be string, object given
And later on i found the mistake. the fix would be to replace the setParameter second input from $someObject to $someString something like this:
$filter->setParameter($name, 'some string which is the real value you want to get later');
I'm trying to use PDO to avoid sql injections and have been looking and searching around for examples and this is what I've come up with, but there are some kind of error somewhere. The database is not getting updated and I get and sql error, but it wont print the details.
elseif (isset($_POST["bilnr"])) {
$name = $_POST['name']; $mobil = $_POST['mobil']; $bilnr = $_POST['bilnr']; $regnr = $_POST['regnr']; $userid = $_COOKIE[userid]; $username = $_COOKIE[user];
$sql=$oDB->Prepare("UPDATE members SET name=:name, mobil=:mobil, bilnr=:bilnr, regnr=:regnr WHERE id=:userid AND username=:username");
$sql->execute(array(':userid' => $userid);
if (!$sql) {
echo "\nPDO::errorInfo():\n";
print_r($oDB->errorInfo());
}
echo "<p class=\"red\">Informasjonen er oppdatert!</p>";
mysqli_close($con); }
If or when I remove the mysqli_close string something crashes and the page just turns blank with no errors. Also with the code above the updates being made in the form dont get into the database.
and the PDO connection in a separate file which is being included
$oDB=new PDO("mysql:host=$host;dbname=$db_name", $username, $password);
Here is the updated code
elseif (isset($_POST["bilnr"])) {
$name = $_POST['name']; $mobil = $_POST['mobil']; $bilnr = $_POST['bilnr']; $regnr = $_POST['regnr']; $userid = $_COOKIE[userid]; $username = $_COOKIE[user];
$sql=$oDB->Prepare("UPDATE members SET name=:name, mobil=:mobil, bilnr=:bilnr, regnr=:regnr WHERE id=:userid AND username=:username");
$sql->execute(array(':userid' => $userid,
':name' => $name,
':mobile' => $mobile,
':bilnr' => $billnr,
':regnr' => $regnr,
':username' => $username));
if (!$sql) {
echo "\nPDO::errorInfo():\n";
print_r($oDB->errorInfo());
}
echo "<p class=\"red\">Update Done!</p>";
mysqli_close($con); }
The next problem is to get the values into the database, as it is now I don't receive any errors so I'm not sure whats wrong.
UPDATE
It works, was just some typo's in the array variables :)
First, you can't mix mysqli and PDO. Second, the problem with your query is that you have 6 placeholders, but you're only filling in one of them when you call execute(). It should be:
$sql->execute(array(':userid' => $userid,
':name' => $name,
':mobile' => $mobile,
':bilnr' => $billnr,
':regnr' => $regnr,
':username' => $username));
The first argument for mysqli_query must be a string (representation of an SQL query) but you are passing it a PDO prepared query.
Don't mix and match multiple database libraries.
Use PDO or mysqli_.
You don't need mysqli_* functions anymore, scrap 'em (only when you're using PDO) :) When you're using PDO, mysql_* and mysqli_* don't work when combining them. I recommend you to use PDO and not mysql functions anymore. PDO is now well established and is the preferred way.
$sql = "
INSERT INTO table (name)
VALUES (:name)
";
//Here you prepare the SQL (you already did that correctly).
$stmt = $db->prepare($sql);
//You can choose to use bindParam, bindValue or include it in the array (as you do it).
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$name = 'John';
$stmt->execute();
This is an example how to insert something into a MySQL database with PDO.
$q = $db->query(" SELECT username FROM users WHERE userident = '1' ");
echo $q; //error
print_r $q; //prints the query information (SELECT ... etc)
How do I go about getting the specific value of the element I am querying? Say the element under column username and where userident equals '1' contains the value "Patrick"; how do I initialize this string into a variable?
//same query as above
$user = $q;
echo $user; //prints "Patrick"
Sorry if this is something so rudimentary and mundane, but I've never done this outside of a foreach() loop. I'd normally iterate through rows to print specific details. The below works, but the foreach() is unnecessary as far as I understand.
foreach($q as $p) {
$user = $p["username"];
}
echo $print; //this correctly prints "Patrick"
Surely there's a method I missed somewhere?
Using the query method pretty much defeats the purpose of using prepared statements. Plus, I believe for what you're looking for, it isn't quite right.
<?php
if (!isset($_POST['id'])) {
exit;
}
$userId = $_POST['id'];
$db = new PDO(/* Stuff */);
$sql = '
SELECT username
FROM users
WHERE id = :id';
// Get a prepared statement object.
$statement = $db->prepare($sql);
// Bind a parameter to the SQL code.
$statement->bindParam(':id', $userId, PDO::PARAM_INT);
// Actually get the result.
$result = $statement->fetch(PDO::FETCH_ASSOC);
// Close the connection.
$statement->closeCursor();
// Print the result.
print_r($result);
Alternately you can use $statement->fetchAll() to gather more than one result.
Edit: I didn't actually run this code, so you might have to tinker with it to get it working right.
im trying to use mysqli with bind_result but all i get is null values. My $stmt
number of rows is greater than 0 so i do have some data in it.
I dont realy understand what value should come into bind_result
I have read at the manual http://php.net/manual/en/mysqli-stmt.bind-result.php
And they dont explain what should i put in the bind_result.
Should i put there the column names? if yes, as strings? how do i get my wanted values?
Here is my code thanks for helping:
$sql = "SELECT * FROM comments WHERE workout_name = ? AND user = ?";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$workout_name = "rytg";
$user = "tomer";
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($comment, $commented_user);
if($stmt->num_rows > 0)
{
$response["workouts"] = array();
while ($stmt->fetch())
{
// temp user array
$workouts = array();
$workouts["comment"] = $comment;
$workouts["user"] = $commented_user;
// push single product into final response array
array_push($response["workouts"], $workouts);
}
}
Your only problem is insufficient error reporting
error_reporting(E_ALL);
ini_set('display_errors',1);
Just add these lines at the top of your code and you will be immediately informed of the exact problem with your code.
Note that on the production server you have to turn displaying errors off and logging on
I don't have a working PHP installation next to me at the moment, so I can't verify it, but I believe you might have to bind both parameters and result before you execute the query, like so:
$workout_name = "rytg";
$user = "tomer";
$stmt = $mysqli->prepare($sql) or trigger_error($mysqli->error."[$sql]");
$stmt->bind_param('ss', $workout_name, $user);
$stmt->bind_result($comment, $commented_user);
$stmt->execute();
I'm not too sure about store_result() either. I don't recall having to use it while retrieving the results, so you might want to try running your code without it and see what happens.