So i have a very simple function that runs against a MySQL database of users with a few other credentials. I have written several other functions that run similar queries with that work as expected. However currently every time I run a query against my DB i get null result. I have taken the query itself and ran it directly against it(phpmyadmin) and was able to retrieve the desired results.
function getName( $user ){
$con = mysqli_connect('localhost','*****','*****','*****');
if(mysqli_connect_error()){
echo 'Failed to Connect: '. mysqli_connect_error();
die();
}
$stmt = $con->prepare('SELECT firstName,lastName FROM users WHERE user=? LIMIT 1');
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt -> bind_result($fname,$lname);
$stmt->fetch();
$lArr = str_split($lname);
$canName = $fname . ' ' . $lArr[0].'.';
return $canName;
}
I have tried with and without limit just in case. var_dump always shows null. Does anyone know why this would happen?
You forgot to ->fetch() any results from the result set, just binding them to variables is not enough
function getName( $user ){
$con = mysqli_connect('localhost','*****','*****','*****');
if(mysqli_connect_error()){
echo 'Failed to Connect: '. mysqli_connect_error();
die();
}
$stmt = $con->prepare('SELECT firstName,lastName FROM users WHERE user=? LIMIT 1');
$stmt->bind_param('s',$user);
$stmt->execute();
$stmt -> bind_result($fname,$lname);
// now fetch data into the bound variables
$stmt->fetch();
$lArr = str_split($lname);
$canName = $fname . ' ' . $lArr[0].'.';
return $canName;
}
You execute the query but you are not picking up the results (As RiggsFolly was saying). You shout use fetch() of fetchall()
http://php.net/manual/en/pdostatement.fetchall.php
http://php.net/manual/en/pdostatement.fetch.php
Related
This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I have a query with a parameter to bind stored in the session.
I tested the query on the database and it should return 1 row but it does not!
I tried everything. Its not an issue with the $id because I use it for another query and it is fully working:
$resultReturn = $con->prepare( 'SELECT `returns`.`return_id`, `returns`.`return_status` FROM
`agents` LEFT JOIN `returns` ON `returns`.`agent_id` = `agents`.`id` AND `agents`.`id` = ?');
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->fetch();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
if($resultReturn)
{
echo $resultReturn->num_rows; //zero
while($row = $resultReturn->fetch_row())
{
echo $resultReturn->num_rows; //incrementing by one each time
}
echo $resultReturn->num_rows; // Finally the total count
}
$con -> close();
the first if returns always FALSE; If I set manually the id it works!
Here is my other query at the beginning of the same page (and its perfectly working):
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// We don't have the password or email info stored in sessions so instead we can get the results from the database.
$stmt = $con->prepare('SELECT password, email, role FROM agents WHERE id = ?');
// In this case we can use the account ID to get the account info.
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->bind_result($password, $email, $role);
$stmt->fetch();
$stmt->close();
It is because I'm using the same connection for multiple queries?
Move fetch() after bind_result().
The correct order should be:
$resultReturn = $con->prepare(/* */);
$resultReturn->bind_param('i', $id);
$resultReturn->execute();
$resultReturn->store_result();
$resultReturn->bind_result($returnID, $returnStatus);
$resultReturn->fetch();
How do I query from a MySQL database when I have a period (.) in string using PHP.
$variable = "my.email#email.com";
$variable = mysqli_real_escape_string($conn, $variable);
$query = "Select * from table WHERE email = '$variable' ";
Apparently this works when I ran it in PhpMyAdmin SQl tab. But when I run it In my code it does not work. Other strings that don't have a period using the same code are working perfectly. What could be the issue
for those who are asking for my original code here it is
//I get the emails from the url
$notit = mysqli_real_escape_string($conn, $_GET['username']);
//I pass my variable in the query
$sql = "SELECT * ";
$sql.=" FROM ordrs ";
$sql.=" WHERE client_email = '$notit' ";
$query=mysqli_query($conn, $sql) or die("try again");
Try this code it works for me try using PDO.
try{
$pdo = new PDO("mysql:host={$db_host};dbname={$db_name}", $db_username, $db_password);
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
$email = "code.sample#mail.co.ke";
$stmt = $pdo->prepare('SELECT email FROM user WHERE email = ?');
$stmt->bindParam(1, $email);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
Sample output by eg: echo '<h2>'. $user['email'] . '</h2>';
You should use prepared statements. Otherwise, possible of sql injection vulnerability.
Example:
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// prepare and bind
$stmt = $conn->prepare("Select * from table WHERE email = ?");
$stmt->bind_param("s", $email);
// set parameters and execute
$email = "john.doe#example.com";
$stmt->execute();
I figured where the issue was the query was fine the error was coming from json_encode which I din't expect . I hope this question helps others in the future who are facing the problem questioned. Thanks for the help
thanks for the help. Cheers
I was using the following code to execute the queries in the database:
$sql = "SELECT * FROM cc_topchoices WHERE location='$location' ORDER BY position asc";
$result = mysqli_query($conn, $sql);
I have read that this way to make the queries is not secure so I want to use the statements prepare() and execute() in php
Now my code looks like this:
$sql = "SELECT * FROM cc_topchoices WHERE location=:location ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->execute(array(":location" => $location));
$result = mysqli_query($conn, $stmt);
But this give me this error:
Fatal error: Call to a member function execute() on boolean
Any idea?
EDIT
Now my code looks like this:
// Create connection
$conn = new PDO("mysql:host=$servername;dbname=$dbname", "$username", "$password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("set names utf8"); //BECAUSE I NEED TO WORK WITH CHINESE LANGUAGE
$sql = "SELECT * FROM cc_topchoices WHERE location=? ORDER BY position asc";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':location', $location);
$stmt->execute(array($location));
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
if ($result > 0) {
// output data of each row
while($row = $stmt->fetch()) {
echo "<li><div><a href='". $row["rest_url"] ."'><img src='images/top_choices/". $row["image"] ."' alt='". $row["alt_desc"]. "' /></a></div></li>";
}
} else {
echo "0 results";
}
is working :) just need to know if this is a good and secure practice
PDO supports named parameters. MySQLi does not. $stmt is false to show you that the SQL you tried to prepare is syntactically malformed. Use ? instead of :location. Check the MySQLi manual for the correct way to use MySQLi. Or, alternately, switch to PDO.
Use below code to fetch records instead of mysqli_query when using pdo statements if your query returns single row.
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo $result['db_column'];
And if return multiple rows:
$stmt->setFetchMode(PDO::FETCH_ASSOC);
while ($result = $stmt->fetch()) {
echo $result['db_column'];
}
And one more thing, always put your prepared statement in try{}..catch{} block.
It will work for you.
I have the below function that i want it to retrieve matching records from MySQL Database:
public function GetUserData($conn){
$username = $_SESSION['username'];
$stmt = $conn->prepare("CALL GetUserData(?)") or die("Query fail: " . mysqli_error($conn));
$stmt->bind_param("s",$username);
$stmt->execute() or die("Query fail: " . mysqli_error($conn));
while($row = $stmt->fetch()){
print_r($row);
}
exit;
}
GetUserData is a stored procedure as below:
CREATE DEFINER=`root`#`localhost` PROCEDURE `GetUserData`(IN `StoredUsername` VARCHAR(255))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGIN
select firstname from users where username=StoredUsername;
END
My problem, is that the print_r($row) only prints "1"
In case the matching rows is two, it prints "11"
I can't seem to figure out what am i using/doing wrong.
Thanks in advance for your assistance.
mysqli_stmt_fetch() is doing not what you think
Username should be passed via parameters
While connection should be a class variable
After getting result, you have to move over additional result returned by procedure, in order to be able to run other queries.
public function GetUserData($username){
$stmt = $this->conn->prepare("CALL GetUserData(?)");
$stmt->bind_param("s",$username);
$stmt->execute();
$data = $stmt->get_result()->fetch_all();
$this->conn->next_result();
return $data;
}
Also, instead of checking result of every database command manually, tell mysqli to throw errors by itself, automatically. Add this line before mysqli_connect and forget all these ugly or die forever:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Can I do a WHERE clause inside an IF statement?
Like I want something like this:
$SQL = mysql_query("SELECT * FROM `table` ORDER BY `row` DESC");
$rows = mysql_fetch_array($SQL);
$email = $_SESSION['email_of_user'];
if($rows["row"] == "1" WHERE `row`='$email' : ?> (Pulls the logged in user's email)
Edit Server
<?php else : ?>
Add Server
<?php endif; ?>
Do I need (" where the WHERE statement is? Because I tried that and it didn't seem to work...
Or can I do it with an if condition inside of a where clause? Not sure of all these terms yet so correct me if I'm wrong...
You cannot mix up a query statement with PHP's statement. Instead write a query extracting desired results and check if there are any rows from that query.
I will show you an example:
$query = "SELECT * FROM `TABLE_NAME` WHERE `field` = '1' && `email`='$email'"; //Create similar query
$result = mysqli_query($query, $link); //Query the server
if(mysqli_num_rows($result)) { //Check if there are rows
$authenticated = true; //if there is, set a boolean variable to denote the authentication
}
//Then do what you want
if($authenticated) {
echo "Edit Server";
} else {
echo "Add Server";
}
Since Aaron has shown such a effort to encourage safe code in my example. Here is how you can do this securely. PDO Library provides options to bind params to the query statement in the safe way. So, here is how to do it.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); //Create the connection
//Create the Query Statemetn
$sth = $dbh->prepare('SELECT * FROM `TABLE_NAME` WHERE field = :field AND email = :email');
//Binds Parameters in the safe way
$sth -> bindParam(':field', 1, PDO::PARAM_INT);
$sth -> bindParam(':email', $email, PDO::PARAM_STRING);
//Then Execute the statement
$sth->execute();
$result = $sth->fetchAll(); //This returns the result set as an associative array