This is my code:
function getUsers($connection ,$username) {
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam("s", $username, PDO::PARAM_STR);
return $stmt->fetchAll();
}
$voornaam = "dave";
$users = getUsers($connection, $voornaam);
print_r($users);
When I open my webpage, I get an empty Array.
I checked, and there is a user with the username "dave" in my database.
This should work, however, it doesn't...
Anyone knows what I did wrong?
Thanks in advance.
First is, you have to execute it before using fetchAll():
$stmt->execute();
$result = $stmt->fetchAll();
This is the correct way:
$stmt = $connection->prepare('SELECT * FROM users where username = :username');
$stmt->bindParam(':username', $username);
If you want to user ? it will determine the order of ? in bindParam, use it like this:
$sql = "SELECT * FROM users where username = ?";
$stmt = $connection->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
More example:
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
Instead of using
$stmt->bindParam("s", $username, PDO::PARAM_STR);
you need to use
$stmt->bindParam(1, $username, PDO::PARAM_STR);
Check this link for details https://www.php.net/manual/en/pdostatement.bindparam
You need to check this Example #2 Execute a prepared statement with question mark placeholders
This is the correct way
$sql = "SELECT * FROM users where username = ?";
$stmt = $conn->prepare($sql);
$stmt->bindParam(1, $username, PDO::PARAM_STR);
$stmt->execute();
return $stmt->fetchAll();
Related
I have an issue I am trying to get the current date when user updates the form. What I am trying to do is instead of posting what the user types in for the date. I wanted the system to get the date. How do I make it so that the update_process.php page gets the current date. In the $_POST[date] bindparam section. I tried adding getdate() in there but that does not work. I am confused on how to do it.
<?php
$serverName = "localhost";
try {
$db= new PDO( "sqlsrv:server=$serverName ; Database=systems_requests", "test", "test");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(Exception $e) {
die( print_r( $e->getMessage() ) );
}
$sql = 'UPDATE requests SET id=:id, studentId= :studentId, name= :name, date= :date WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->bindParam(':date', $_POST['date'], PDO::PARAM_STR);
try {
$stmt->execute();
} catch(PDOException $exception) {
echo "Error: " . $exception->getMessage();
}
?>
also how would I change the count to reflect that to count how many Bob's signed up with todays date.
<?php
$stmt = $db->prepare("SELECT COUNT(*) AS rows_cnt FROM students WHERE name='Bob' AND date=getdate()");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['rows_cnt'];
}
?>
To fix my issue I had to remove set ID in order for the update to work.
$sql = 'UPDATE requests SET studentId= :studentId, name= :name, date=getdate() WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
$sql = 'UPDATE requests SET id=:id, studentId= :studentId, name= :name, date=getdate() WHERE id= :id';
$stmt = $db->prepare($sql);
$stmt->bindParam(':id', $_POST['id'], PDO::PARAM_INT);
$stmt->bindParam(':studentId', $_POST['studentId'], PDO::PARAM_STR);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
Like I said in the comments, I'm not sure what the role of $_POST['date'] is, so why are you using it? From your question, it seems like you just want the current date, not user input. In that case, you don't need to bind a parameter, you just put the date function in the query.
I am trying to sum the values from a column using mysqli prepared statement with the code below but is not working. Does anyone can help me pointing what I am doing wrong? Thanks!
$stmt2 = $mysqli->prepare("SELECT SUM(col) as total FROM tb_a WHERE user=?");
$stmt2->bind_param("s", $user);
$stmt2->execute();
$op_row = $stmt2->fetch_assoc();
echo $op_row['total'];
Give this a go:
$user = "Larry"; // example
$stmt = $mysqli->prepare("SELECT SUM(col) FROM tb_a WHERE user=?");
$stmt->bind_param("s", $user);
$stmt->execute();
$stmt->bind_result($total);
$stmt->fetch();
echo $total;
or
$user = "Robert"; // example
$stmt = $mysqli->prepare("SELECT SUM(col) FROM tb_a WHERE user=?");
$stmt->bind_param("s", $user);
$stmt->execute();
$stmt->bind_result($total);
while ($stmt->fetch()) {
echo $total;
}
Try this:
$stmt2 = $mysqli->prepare("SELECT SUM(col) as total FROM tb_a WHERE user=?");
$stmt2->bind_param("s", $user);
$stmt2->execute();
$res = $stmt2->get_result();
$row = $res->fetch_assoc();
The prepared statement object do not have a fetch_assoc() method so you should first use get_result() and the result of that has a fetch_assoc()
Try this
$conn = new mysqli;
$sum = "SELECT SUM(col) as total FROM tb_a WHERE user=?";
$stmt = $conn->prepare($sum);
$stmt->bind_param("s", $user);
$sum= $stmt->execute();
This code is used to login using authentication , session management. error comes in 15th line of code which is fatal error: call to a member function bindParam() on non-object. i am not understanding that where is the mistake done by me. please help me.
<?php
// Sanitize incoming username and password
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$pwd= md5($password);
// Connect to the MySQL server
$db = new mysqli("localhost", "root", "", "login");
// Determine whether an account exists matching this username and password
$stmt = $db->prepare("SELECT id FROM accounts WHERE username =$username and password =$pwd");
// Bind the input parameters to the prepared statement
// the error comes in this line
$stmt->bindParam('ss', $username, $pwd);
// Execute the query
$stmt->execute();
// Store the result so we `enter code here`can determine how many rows have been returned
$stmt->store_result();
if ($stmt->num_rows == 1) {
// Bind the returned user ID to the $id variable
$stmt->bind_result($id);
$stmt->fetch();
// Update the account's last_login column
$stmt = $db->prepare("UPDATE accounts SET last_login = NOW() WHERE id=$id");
$stmt->bind_param('d', $id);
$stmt->execute();
$_SESSION['username'] = $username;
// Redirect the user to the home page
header('Location: home.php');
}
?>
$stmt = $db->prepare("SELECT id FROM accounts WHERE username =$username and password=$pwd");
$stmt->bindParam('ss', $username, $pwd);
You're binding a parameter that does not exist. You're also trying to bind two parameters with a single call.
Docs for the relevant function
Sample (taken from php.net) :
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
?>
[edit]
Looks like this was actually about mysqli. Relevant doc
Relevant sample:
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$stmt->bind_param('sssd', $code, $language, $official, $percent);
I want to use a single database connection with multiple queries but use prepare and bind_param. How can i do this? I cant find it in the documentation.
Edit: i want two completely different queries.
$db = getConnection();
$query = "INSERT INTO talks(title, body, topic) VALUES(?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('sss', $title , $body, $topic);
$stmt->execute();
$stmt->close();
$query = "SELECT * WHERE title=?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $title);
$stmt->execute();
$stmt->bind_result($i, $t, $b, $to);
$stmt->fetch();
$id = $i;
$stmt->close();
Its telling me that $stmt isnt an object on the second go around
Just prepare a second query, as you did with the first.
$conn = new mysqli(....);
$stmt = $conn->prepare(....);
//Do stuff with $stmt
$stmt = $conn->prepare(...different...); //$stmt is overridden with the new query.
//Do stuff with the new $stmt.
I am trying to execute the following sql from php using pdo: SELECT * FROM my_table WHERE name=?.
When I do this:
$sql = 'SELECT * FROM my__table WHERE name=?' ;
$stmt = $dbconn->prepare($sql);
$stmt->bindValue(1, $_POST['name'], PDO::PARAM_STR);
$stmt->execute();
I get an empty result set.
When I do this:
$sql = 'SELECT * FROM my__table WHERE name=\''.$_POST['name'].'\'' ;
$stmt = $dbconn->prepare($sql);
$stmt->execute();
I get the row that I need.
The column 'name' is a VARCHAR(32). This bug only happens with strings. When the bound parameter is an sql INTEGER everything works like it is supposed to.
I am using sqlite3, php 5.2.6 under Apache on Ubuntu.
Both of these should work:
Without using binding
$sql = "SELECT * FROM my__table WHERE name = ? " ;
$stmt = $dbconn->prepare($sql);
$stmt->execute(array($_POST['name']));
Using a named parameter
$sql = "SELECT * FROM my__table WHERE name = :name " ;
$stmt = $dbconn->prepare($sql);
$stmt->bindParam(':name', $_POST['name'], PDO::PARAM_STR);
$stmt->execute(array($_POST['name']));
What about this?
$sql = "SELECT * FROM my__table WHERE name='?'" ;
$stmt = $dbconn->prepare($sql);
$stmt->bindValue(1, $_POST['name'], PDO::PARAM_STR);
$stmt->execute();