MySQLi - Get table value as string instead of object - php

I'm trying to use php to retrieve both the name and userEmail values from my Users MySQL table seen here:
I'm using the following code in attempt to grab the currently logged-in user's name and userEmail:
<?php
session_start();
#connect to MySQL database
require_once("settings.php");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
#get username of current session
$username = $_SESSION['username'];
#get userEmail of logged-in user from database
$sql = "SELECT userEmail from Users WHERE username LIKE '{$username}' LIMIT 1";
$result = $mysqli->query($sql);
$replyTo = mysqli_fetch_field($result);
#get name of logged-in user from database
$sql2 = "SELECT name from Users WHERE username LIKE '{$username}' LIMIT 1";
$result2 = $mysqli->query($sql2);
$name = mysqli_fetch_field($result2);
?>
Then I try passing the $replyTo and $name values into a function that only accepts strings (the setFrom() function from PHPmailer to be precise):
$mail->setFrom($replyTo, $name);
...and get the following errors:
Warning: trim() expects parameter 1 to be string, object given in /var/www/phpmailer/class.phpmailer.php on line 489 (this object was $replyTo)
Catchable fatal error: Object of class stdClass could not be converted to string in /var/www/phpmailer/class.phpmailer.php on line 490 (this object was $name)
Using Chrome Logger to debug, I found these to be the values of $userEmail and $name:

I think you can get email and name with single query - make use of prepared statement for security reason(SQLIA)
#get userEmail of logged-in user from database
$sql = "SELECT userEmail,name from Users WHERE username = ? LIMIT 1";
// this is prepared statement and prevent form sql injection attack
$statement = $mysqli->prepare($sql);
$statement->bind_param('s',$username);
$statement->execute();
$result = $statement->get_result();
// fetch first record in associative array
$userDetail = $result->fetch_assoc();
if($userDetail)
{
$replyTo = $userDetail['userEmail'];
$name = $uerDetail['name'];
$mail->setFrom($replyTo, $name);
}
else
{
echo 'user not found';
}

Related

Error "Cannot use object as array" when trying to set content of column as variable

I use IDs rather than usernames as I find them easier to handle, and as a result I need to access the database first when I want to display a username.
$userid = $_SESSION['userid'];
$sql = "SELECT * FROM users.users WHERE id = $userid";
$user = $pdo->query($sql);
$username = $user['name'];
But when doing so I get an error: Uncaught Error: Cannot use object of type PDOStatement as array. In theory my code should set $userid as the ID of the currently logged in user, select the corresponding row in users.users and set $username as the name column, with which I can work then. How can I convert the PDOStatement to be usable?
PDO::query returns a PDOStatement object, to get the values from it you need to perform a fetch:
$userid = $_SESSION['userid'];
$sql = "SELECT * FROM users.users WHERE id = $userid";
$stmt = $pdo->query($sql);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
$username = $user['name'];

First time trying I'm working on Login/register form. Getting an error

Hey guys I'm working on a login/register for and I'm struggeling with the following things. When registering there's a message (registration complete) but there's also an error I can't get rid off.
Als when the username is already taken there should be a message that says that but there isn't. The error I get is the following.
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, bool
given in C:\xampp\htdocs\test\registration.php on line 16
The code I use in registration.php is
<?php
session_start();
$con = mysqli_connect('127.0.0.1','jstam','12345');
mysqli_select_db($con, 'userregistration');
$name = $_POST['user'];
$pass = $_POST['password'];
$s = "select * from usertable where name = 'name' && passoword = '$pass'";
$result = mysqli_query($con, $s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Gebruikersnaam in gebruik";
}else{
$reg= "insert into usertable (name , password) values ('$name' , '$pass')";
mysqli_query($con, $reg);
echo"Registratie succevol";
}
?>
I believe you may have a typo in your code
$s = "select * from usertable where name = 'name' && passoword = '$pass'";
I assume that passoword should be password. Also, name should be $name
$s = "select * from usertable where name = '$name' && password = '$pass'";
As others have suggested, your code is vulnerable to SQL injection and should NOT be used in production.

Unable to concatenate sql in pdo statement [duplicate]

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."' ";

PHP and MySQL Select a Single Value [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I'd like to know how to select a single value from my MySQL table. The table includes columns username and id amongst others (id is auto-increment and username is unique). Given the username, I want to set a session variable $_SESSION['myid'] equal to the value in the id column that corresponds to the given username. Here's the code that I've already tried:
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
$_SESSION['myid'] = $value;
So far I'm getting:
Catchable fatal error: Object of class stdClass could not be converted to string.
Casting $value to type string does not fix the problem.
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
You do this by using mysqli_fetch_field method.
session_start();
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' limit 1";
$result = mysqli_query($link, $sql);
if ($result !== false) {
$value = mysqli_fetch_field($result);
$_SESSION['myid'] = $value;
}
Note: you can do that by using mysql_fetch_field() method as well, but it will be deprecated in php v5.5
mysql_* extension has been deprecated in 2013 and removed completely from PHP in 2018. You have two alternatives PDO or MySQLi.
PDO
The simpler option is PDO which has a neat helper function fetchColumn():
$stmt = $pdo->prepare("SELECT id FROM Users WHERE username=?");
$stmt->execute([ $_GET["username"] ]);
$value = $stmt->fetchColumn();
Proper PDO tutorial
MySQLi
You can do the same with MySQLi, but it is more complicated:
$stmt = $mysqliConn->prepare('SELECT id FROM Users WHERE username=?');
$stmt->bind_param("s", $_GET["username"]);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();
$value = $data ? $data['id'] : null;
fetch_assoc() could return NULL if there are no rows returned from the DB, which is why I check with ternary if there was any data returned.
Since PHP 8.1 you can also use fetch_column()
$stmt->execute();
$value = $stmt->get_result()->fetch_column();
Try this
$value = mysql_result($result, 0);
When you use mysql_fetch_object, you get an object (of class stdClass) with all fields for the row inside of it.
Use mysql_fetch_field instead of mysql_fetch_object, that will give you the first field of the result set (id in your case). The docs are here
It is quite evident that there is only a single id corresponding to a single username because username is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
O/P
+----+
| id |
+----+
| id |
+----+
i.e. 'id' actually is treated as a string not as the id attribute.
Correct synatx:
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
Complete code
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
try this
session_start();
$name = $_GET["username"];
$sql = "SELECT 'id' FROM Users WHERE username='$name' LIMIT 1 ";
$result = mysql_query($sql) or die(mysql_error());
if($row = mysql_fetch_assoc($result))
{
$_SESSION['myid'] = $row['id'];
}

Can't retrieve DB info

I need help figuring out why the following DB Query is not working. I know the DB connection is good. I also know the $referralname = $_SESSION['user_name']; is correctly rendering. It has to be something with my code.
I am getting the following errors. Maybe this will help to figure this out.
[12-Jun-2013 21:13:54 America/New_York] PHP Warning: mysql_query() expects parameter 1 to be string, object given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 89
[12-Jun-2013 21:13:54 America/New_York] PHP Warning: mysql_num_rows() expects parameter 1 to be resource, null given in /x/x/public_html/americansolar/partner/classes/Referral.php on line 90
P.S. I am not sure if the while statement is necessary or not since it will always only return one result???
My Code:
// creating a database connection
$this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// if no connection errors (= working database connection)
if (!$this->db_connection->connect_errno) {
$referralname = $_SESSION['user_name'];
// get the referrer's id
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
$result = MYSQL_QUERY($query_get_referral_id);
$numberOfRows = MYSQL_NUM_ROWS($result);
$i = 0;
while ($i<$numberOfRows)
{
$thisId = MYSQL_RESULT($result,$i,"user_id");
$i++;
}
}
My Solution:
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
while($row = mysqli_fetch_array($query_get_referral_id))
{
$thisId = $row['user_id'];
}
Youre mixing mysqli and mysql... they are two completely different and incompatible interfaces. Secondly, your $query_get_referral_id is not an id value... it is a mysqli_result object. You need to then extract the value from that object.
And lastly... DONT use mysql... stick with mysqli, or use PDO
Also you should use a prepared statement for this:
$stmt = $this->db_connection->query("SELECT user_id From users WHERE user_name = ?");
$stmt->bind_param('s', $referralname);
$stmt->execute();
if($stmt->num_rows) {
$stmt->bind_result($userId);
while($stmt->fetch()) {
// do something with $userId...
// each iteration of this loop is a
// row of the result set, it will automatically
// load the value of the user_id into $userId
}
}
I donot think you should query like
$query_get_referral_id = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");
$result = MYSQL_QUERY($query_get_referral_id);
Well, you should go
$result = $this->db_connection->query("SELECT * From users WHERE user_name = '".$referralname."';");

Categories