I have a function which retrieves user information and stores it in variables like so within a class:
public function UserInformation() {
$query = "SELECT * FROM users WHERE username = '$this->user'";
try {
$stmt = $this->db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetch();
$email = $rows['email'];
$username = $rows['username'];
}
How would I then display a single variable from that function? I've tried echo $retrieveInfo->UserInformation->username; with no success, how would I do this?
You have defined local variables, that to be lost as soon as function ends its execution.
The more correct way of doing what you want would be to return the data from the function like:
$rows = $stmt->fetch();
return $rows;
And call the method like
$rows = $yourObject->UserInformation();
Or, if the object represents a particular user you could store the data retrieved in an instance members like:
$this->email = $rows['email'];
and then access them
$yourObject->email
This would work as well while the former is what I would prefer (I don't know the whole task though)
Related
Why is this not working:
function listOrderComments ($factnr){
global $connection;
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = '$factnr'";
$result = mysqli_query($connection, $query);
When I echo $factnr I get "123" back.
When I uncommented //$factnr = 123; my function is working.
Looked everywhere for a solution. check the type $factnr is (string).
Well if you're using a variable in your query you're opening yourself up to an injection attack for one.
If you're going to be using that variable I would recommend you use bind_param for your query
Read the PHP manual link below and you will be able to figure out the issue
http://php.net/manual/en/mysqli-stmt.bind-param.php
If you're passing in a variable to your function it should already be set so I don't understand why you're setting it to 123 anyway. So execute the sql statement and bind the parameter following the first example on the PHP docs page.
public function listOrderComments ($factnr)
{
global $connection;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ?";
$sql->prepare($query);
$sql->bind_param("s", $factnr);
$sql->execute();
$result = $sql->get_result();
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach ($data as $row) {
print_r($row);
}
}
Then do what you want with the result
You can go with:
$query = "SELECT * FROM orderstatus WHERE factuurnummer = ". $factnr;
Concatenating your code is not good practise. Your best solution is to use PDO statements. It means that your code is easier to look at and this prevents SQL injection from occuring if malice code slipped through your validation.
Here is an example of the code you would use.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$factnr = "123" // or where-ever you get your input from.
$query = "SELECT * FROM orderstatus WHERE factuurnummer = :factnr";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("factnr" => $factnr);
$statement->execute($statementInputs);
//Returns results as an associative array.
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
//Shows array of results.
print_r($result);
?>
Use it correctly over "doted" concat. Following will just work fine:
$factnr = 123;
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
UPDATE:
here is $factnr is passing as argument that supposed to be integer. Safe code way is DO NOT use havvy functions even going over more complicated PDO, but just verify, is this variable integer or not before any operation with it, and return some error code by function if not integer. Here is no danger of code injection into SQL query then.
function listOrderComments ($factnr){
global $connection;
if (!is_int($factnr)) return -1
//$factnr = 123; //or $factnr = "123"; (Both work)
$query = "SELECT * FROM orderstatus WHERE factuurnummer = " . $factnr;
$result = mysqli_query($connection, $query);
When I use the code below I get Undefined Index: email on $row['email']. If I grab the whole array with $row and print_r, it displays like it should.
Where am i going wrong ?
$stmt = $db->dbh->prepare("SELECT email FROM $this->table WHERE `email`= :email");
$stmt -> bindValue(':email', $email);
$stmt->execute();
while ($row = $stmt->fetchAll()){
return $row['email'];
}
$new = new Users;
echo $new->reset_password($email);
}
fetchAll returns a 2-dimensional array of all the results. To get just one row at a time, you should call $stmt->fetch(), not $stmt->fetchAll().
while ($row = $stmt->fetch()) {
...
}
But since you're returning, you shouldn't use a loop at all. The return statement will terminate the loop after the first iteration. Just use an if statement.
if ($row = $stmt->fetch()) {
return $row['email'];
}
This whole code doesn't make much sense -- $newemail is guaranteed to be the same as $email, why are you returning it? It probably should be:
if ($stmt->fetch()) { // Email was found
return true;
} else {
return false;
}
to check if the email entered in the db,
$stmt = $db->dbh->prepare("SELECT 1 FROM $this->table WHERE email= ?");
$stmt->execute([$email]);
return $stmt->fetchColumn();
You should use this code:
while ($row = $stmt->fetch()){
$newemail = $row['email'];
}
Instead of this code:
while ($row = $stmt->fetchAll()){
$newemail = $row['email'];
}
Method fetchAll() fetches all rows in a single call, method fetch() fetches only current row and moves pointer to the next row.
Documentation to method fetch() can be found here and documentation to method fetchAll can be found here.
I'm using PDO to grab records from a mysql table. The data will be encoded with json_encode() and printed through the Slim framework for the API:
$app->get('/get/profile/:id_user', function ($id_user) use ($app) {
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
try {
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC); // THIS!!!
if($stmt->rowCount()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
} catch(PDOException $e) {
echo $e->getMessage();
}
});
Should I use
$data = $stmt->fetch(PDO::FETCH_ASSOC);
or
$data = $stmt->fetchObject();
? Any direct benefits on fetching the data as an object? I've read some examples but they never explain why. The only usage for the resulting data will be to print it in JSON format. Thanks!
It doesn't matter. Though I'd cut an object out with Occam's razor.
Also your code is slightly wrong and redundant. Here is a proper version
$sql = 'SELECT * FROM user WHERE id_user = :id_user';
$stmt = cnn()->prepare($sql);
$stmt->bindParam(':id_user', $id_user, PDO::PARAM_INT);
$stmt->execute();
if ($data = $stmt->fetch()) {
$app->etag(md5(serialize($data)));
echo json_encode($data,JSON_PRETTY_PRINT);
} else {
$app->notfound();
}
there is no point in setting fetch mode for the every query when you can set it globally.
numrows() call is also useless.
and of course catching an exception is redundant, insecure and unreliable.
I'm trying to fetch results using mysqli->fetch_row() (or fetch_object(), fetch_array()), yet when I go to run the code at run time it gives me the following error:
Fatal error: Call to a member function fetch_row() on a non-object in...on line 23.
The var in question that does this is $results in the code below. $user and $password gain their values from another .php file that this file is being included in so that's not really important at the moment. Now correct me if I'm wrong but if $results is being set = to $db->query($query) then isn't it supposed to inherit the properties of $db aka the mysqli class?
class mySQLHelper{
public function checkPass($user, $pass){
global $db;
$db = new mysqli();
$db->connect('localhost', 'root', '', 'mydb');
if (mysqli_connect_errno()){
echo 'Can not connect to database';
echo mysqli_connect_errno(). mysqli_connect_error();
exit;
return false;
}
$query = "SELECT user, password FROM Users WHERE user = $user AND password = $pass " ;
echo $query;
$results = $db->query($query);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
$results->close();
$url = 'http://'. $_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/";
if(!$results){
// mysqli_close($db);
// header("Location:.$url.login.php&msg=1");
}
else{
// mysqli_close($db);
// header("Location:.$url.featured.php");
}
}
}
Your query is failing on this line:
$results = $db->query($query);
Because of this, $results is false - not a result object as you expect.
To fix the issue, you need to add quotes around your variables (or use prepared statements):
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
I would suggest updating to use a prepared statement to prevent SQL-injection issues too though:
$stmt = $db->prepare('SELECT user, password FROM Users WHERE user = ? AND password = ?');
$stmt->bind_param('ss', $user, $pass);
$stmt->execute();
$results = $stmt->get_result();
You script is lacking error checking, and therefore the error in the query is not handled.
$query = "SELECT user, password FROM Users
WHERE user = '$user' AND password = '$pass' " ;
// ^ quotes needed
echo $query;
$results = $db->query($query);
// handle a error in the query
if(!$results)
die($db->error);
while ($row = $results->fetch_row()){
echo htmlspecialchars($row->user);
echo htmlspecialchars($row->password);
}
If you user & password field text or varchar, then you need to use single quote around them
$query = "SELECT user, password FROM Users WHERE user = '".$user."' AND password = '".$pass."' " ;
You have to check, if query runs properly:
if ($result = $mysqli->query($query))
{
}
Use: var_dump($results) to check what it contains
Why are you checking if($results) after trying to manipulate it?
This...
$results->close();
//...
if(!$results){
//...
}
Should be...
if(!$results){
//...
}
$results->close();
So I am bashing my head against the wall over a question which more than likely has a simple solution. Here is my code.
public function login($username, $password){
$sql = "SELECT * FROM users WHERE username = :user AND password = :pass";
$stmt = $this->pdo->prepare($sql);
$data = array('user' => $username, 'pass' => md5($password . $this->salt));
$stmt->execute($data);
$status = $stmt->fetchColumn();
if($status){
echo "You are Logged in!";
print_r($result);
} else {
echo $status;
$this->error['alert'] = "You have not entered the correct login information.";
Users::ErrorReport();
}
}
What I want to do is pull all of the data from that users row and store it in an array so that I can access it in order to store it to the class variables. I would like to do something similar to
while($row = $stmt->fetchAll()){
$this->username = $row['username'];
}
The problem when I do this is Ive run into a million nasty errors and cant find any solutions while searching the net.
Use fetch() instead of fetchAll()
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$this->username = $row['username'];
}
or if you like, you can use fetchAll() this way
$result_array = $stmt->fetchAll(PDO::FETCH_ASSOC)
Update: Venu is right, it's a bit wasteful to use mixed (Numeric and Associative) if you're only gonna use associative. So it's a good idea to use PDO::FETCH_ASSOC