Mysqli_fetch_assoc with params instead - php

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

Related

Prepared statement returns no results

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.

Using PHP variable in SQL query

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.

PDO: When to use bindParam, execute(array)) and PDO::FETCH_ASSOC?

I'm new to PDO, in fact, this is the first time that I'm using it. All the while I've been using mysql which is depreciated. And so recently, I'm trying to update all my site to use PDO which is better and safer according to many sources that I found from the internet.
However, those tutorials is making me even more curious and full of questions. I've been google for the whole day and I still can't get the best answer or examples.
Let's start by this code below,
// query
$sql = "SELECT title FROM books ORDER BY title";
$q = $conn->query($sql);
$q->setFetchMode(PDO::FETCH_ASSOC);
// fetch
while($r = $q->fetch()){
print_r($r);
}
I do understand that it fetches the data just like mysql_fetch_assoc. But, here's another code that I found from the net.
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name');
$stmt->execute(array('name' => $name));
foreach ($stmt as $row) {
// do something with $row
}
and lastly, this:
$stm = $pdo->prepare('SELECT * FROM table LIMIT ?, ?');
$stm->bindParam(1, $limit_from,PDO::PARAM_INT);
$stm->bindParam(2, $per_page,PDO::PARAM_INT);
$stm->execute();
$data = $stm->fetchAll();
Why are there so many different methods to fetch a data ?
I somehow found out that with bindParam, you're able to set integer or strings for the variable? But with this below...
$pdo->execute(array(':col2' => $col2, ':col3' => $col3, ':col4' => $col4));
Am I still able to mix integer and strings without declaring if it's integer or strings?
Is it ok if I do like this ? mixing strings and integer in execute array...
$sql = "INSERT INTO books (id,author) VALUES (:id,:author)";
$q = $conn->prepare($sql);
$q->execute(array(':author'=>'string', ':id'=>1));
And also, does all codes above avoid SQL injection ?
I somehow prefer the execute array method as it is shorter and I don't want to declare if it's integer or strings every time like using the bindParam method.

Php pdo result array

I have a select to a database what should get a number and display it, but display just array
$sth = $conn->prepare("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
echo $result;
What can I do to display that number?
You don't prepare anything so you don't need to use prepared statements just use query like this:
$result = $conn->query("SELECT score FROM people WHERE email='gasd3z#yaho.com'");
foreach($result as $row)
echo $row['score'];
The previous answer is wrong, but not much.
When you're doing fetchAll(), you're getting all of the rows matching query from the database.
The answer is
$sth = $conn->prepare("SELECT score FROM people WHERE email=:email");
$sth->execute([':email' => 'gasd3z#yaho.com']);
$result = $sth->fetch(PDO::FETCH_ASSOC);
$sth->closeCursor();
echo $result['score'];
And don't forget that prepare() is for preparing statements, so you better want to have user data in query just like in my example. If you don't want to process any values in query, use query() or exec() instead.
You can print out arrays with print_r($result) or var_dump($result). Echoing only prints out the type.
Also, if you only need to print out a specific line, do it like echo $result['score'];

Alternative of mysqli get_restult if I don't want use bind_result and fetch

When I use something like this:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?');
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
according this answer:
How can I prevent SQL injection in PHP?
I get this error:
Call to undefined method mysqli_stmt::get_result()
Because get_result is available only with mysqlnd (get_result php reference).
So is there any alternative how to get all columns? If I don't want bind all columns(using bind_result()), because in my case I do query on 3 tables and I just dont want bind all columns because it is an insane job.
So I don't want use bind_result(), get_resuslt doesn't work is there any alternative or it means I cant use prepared statements and only chance is get back to this:
sql = "SELECT * FROM ...." //just some query
$query = mysqli_query($db_donnection, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$id = $row["id"];
$e = $row["email"];
//....
}

Categories