I have been chasing my tale with this for a long time. I have not been able to find an issue with this code:
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
echo $stmt->num_rows." ".$username;`
The CUSTOMER table in my database has three columns: username, pwd, and email. But nonetheless, no results are returned when I assign the $username variable to a value I know exists in the database. I know it exists because this query
$results = $db->query("SELECT * FROM CUSTOMER WHERE username ='$username'");
echo $results->num_rows;
Displays one row, which is what is expected. Can anybody please tell me why my prepared statement will not produce the correct results? I have tried several variations of quoting, not quoting, hardcoding the variable's value, but nothing works. I am on a university server so I have no control over PHP's or MySQL's settings, but I'm not sure that has anything to do with it. It seems like a coding issue, but I can't see anything wrong with the code.
num_rows will be populated only when you execute $stmt->store_result();.
However, 99.99% of the time you do not need to check num_rows. You can simply get the result with get_result() and use it.
$query = "SELECT * FROM CUSTOMER WHERE username = ?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
foreach($result as $row) {
// ...
}
If you really want to get the num_rows, you can still access this property on the mysqli_result class.
$result = $stmt->get_result();
$result->num_rows;
You've executed the query successfully, but not done anything with the result. After $stmt->execute();, you're looking for $stmt->bind_result($result);.
With this, you'll have access to the user's information in the $result variable.
Related
I'm trying to get messages sent to a user by others and output them all through a while loop. However the current system I have doesn't output anything at all?
I searched this site for a solution and each one I found I would try but to no avail. I have tried multiple fetch methods and can't seem to figure it out.
This is the main script that does the magic
$userid=$_SESSION['id'];
$stmt = $conn->prepare('SELECT * FROM messages WHERE user2_id = ?');
$stmt->bind_param('i', $userid);
$stmt->execute();
$result=$stmt->get_result();
$row=$result->fetch_assoc();
//echo $row['message_text'];
while ($row = $result->fetch_assoc()) {
echo "<p>".$row['message_text']."</p>";
}
No error messages show up at all.
$sql = "SELECT firstName , lastName FROM People WHERE born='1934'" ;
$stmt = $db->prepare($sql);
echo "<p>Execute the SQL-statement:<br><code>$sql</code><p>";
$stmt->execute();
// Get the results as an array with column names as array keys
$res = $stmt->fetchColumn();
$stmt->execute();
$res2 = $stmt->fetchColumn(1);
$ANSWER = $res." ".$res2;
If i remove the second execute(); statement the $res2 variable is empty.
Why is that? When i already have retrieved the results once/executed the statement.
if i input 1 as the parameter in the first fetchColumn(); i get the lastName DB column, so the results are there already.
The reason i'm using fetchColumn(); is that i need the result as string and not an array. I just cant understand why it doesnt work without the second execute, it seems like the result set gets destroyed or something after the first fetch and i need to execute it again? That sounds weird.
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.
Thank you in advance.
Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:
<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";
$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
echo $row['value'];
}
?>
I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.
Thanks again.
Do it like so
<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
$stmt->bind_param("s",$q); // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
$stmt->execute();
$stmt->bind_result($col1,$col2,$col3,$col4); // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
$stmt->store_result();
while($stmt->fetch()){ // fetch the results
echo $col1;
}
$stmt->close();
}
?>
Yes mysql_real_escape_string() is deprecated.
One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.
To continue using the mysqli_* functions, use:
mysqli_prepare() to get a prepared statement
mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')
mysqli_stmt_execute() to execute the statement
mysqli_stmt_bind_result() to send the output to a variable.
<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
$statement = mysqli_prepare($conn, $query);
//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);
//execute the statement
mysqli_stmt_execute($statement);
//bind an output variable
mysqli_stmt_bind_result($stmt, $value);
while ( mysqli_stmt_fetch($stmt)) {
echo $value; //print the value from each returned row
}
If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.
I am new to PHP and have a really basic question.
If I know the result of a query is only a single value (cell) from a single row in MySQL how can I simplify the below without having to go through an array of results and without increasing the risk of SQL injection ?
In the example below I would just need to echo a single email as the result of the query.
I found a couple of posts suggesting different approaches with fetch_field for this but I am not sure what is the best way here since some of these seem to be pretty old or deprecated now.
My PHP:
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$result = $stmt->get_result();
$arr = $result->fetch_assoc();
echo $arr["email"];
Many thanks in advance.
You can avoid caring what the column is called by just doing this:
<?php
$stmt = $conn->prepare("SELECT email FROM Users WHERE userName = ? LIMIT 1");
$stmt->bind_param('s', $userName);
$stmt->execute();
$email = $stmt->get_result()->fetch_object()->email;
echo $email;
I'm trying to patch over to params from standard mysqli. I canĀ“t wrap my head around how to target the columns i want with the new way to get results from db. lets say i have table with id, firstname, lastname, and about.
$query = mysqli_query($con, $sqlstmt);
while($row = mysqli_fetch_assoc($query){
$row['firstname'];
$row['about'];
}
this is easily done however when i try to use params,execute etc i cant really wrap it.
$stmt = mysqli_prepare($connect, "SELECT * FROM medlemmar WHERE firstname=?");
mysqli_stmt_bind_param($stmt, 's', $firstname,);
mysqli_stmt_execute($stmt);
I don't know how to fetch results from specific columns when using second choice and how to make an array of it etc.
In normal case i would just do
$array[]= $row['firstname']
When you use prepared statements, it takes one extra step to get the mysqli_result resource from the statement. Then you can use it like you used the mysqli_result you got from mysqli_query().
$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$row['firstname'];
$row['about'];
}
This usage requires mysqlnd, which is enabled by default in PHP 5.4+.
If you don't have mysqlnd, you have to bind results, like shown in the answer from #joaofgf.
It's worthwhile to upgrade to mysqlnd for its extra features and better performance.
you should use the associative bind stmt_bind_assoc()
example:
$stmt = $mysqli->prepare("SELECT name, userid FROM somewhere");
$stmt->execute();
$row = array();
stmt_bind_assoc($stmt, $row);
// loop through all result rows
while ($stmt->fetch()) {
print_r($row);
}
source: http://www.php.net/manual/en/mysqli-stmt.fetch.php