mysql ->fetch_all() not working - php

Please shame me. What's not right here? I was hoping for something like ->fetch_all(Opt), a one liner, to place all the results in an array but couldn't make it work. This is what I wound up doing:
$s = "select id, username from users";
$conn = db_connect();
$sth = $conn->prepare($s);
$sth->execute();
$sth->bind_result($id, $un);
$ida = array();
while ($sth->fetch()) {
$ida[] = $id;
}
I tried
$r = $sth->fetch_all() (tried assigning and not assigning a return value) both using and not using ->bind_result()
but both failed. What am I doing wrong?

First off, make sure that you have mysqlnd on your environment.
Then, to use ->fetch_all(), you'll need to use ->get_result() method first.
Here's the sequence:
$s = "select id, username from users";
$conn = db_connect();
$sth = $conn->prepare($s);
$sth->execute();
$data = $sth->get_result(); // get result first
$result = $data->fetch_all(MYSQLI_ASSOC); // then fetch all
print_r($result);

Related

How to check if column equals a value and do somthing if true? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 2 years ago.
I am trying to write a function that will check for a single value in the db using mysqli without having to place it in an array. What else can I do besides what I am already doing here?
function getval($query){
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
$result = $mysqli->query($query);
$value = $mysqli->fetch_array;
$mysqli->close();
return $value;
}
How about
$name = $mysqli->query("SELECT name FROM contacts WHERE id = 5")->fetch_object()->name;
The mysql extension could do this using mysql_result, but mysqli has no equivalent function as of today, afaik. It always returns an array.
If I didn't just create the record, I do it this way:
$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];
Or if I did just create the record and the userID column is AI, I do:
$userID = mysqli_insert_id($link);
Always best to create the connection once at the beginning and close at the end. Here's how I would implement your function.
$mysqli = new mysqli();
$mysqli->connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
$value_1 = get_value($mysqli,"SELECT ID FROM Table1 LIMIT 1");
$value_2 = get_value($mysqli,"SELECT ID FROM Table2 LIMIT 1");
$mysqli->close();
function get_value($mysqli, $sql) {
$result = $mysqli->query($sql);
$value = $result->fetch_array(MYSQLI_NUM);
return is_array($value) ? $value[0] : "";
}
Here's what I ended up with:
function get_col($sql){
global $db;
if(strpos(strtoupper($sql), 'LIMIT') === false) {
$sql .= " LIMIT 1";
}
$query = mysqli_query($db, $sql);
$row = mysqli_fetch_array($query);
return $row[0];
}
This way, if you forget to include LIMIT 1 in your query (we've all done it), the function will append it.
Example usage:
$first_name = get_col("SELECT `first_name` FROM `people` WHERE `id`='123'");
Even this is an old topic, I don't see here pretty simple way I used to use for such assignment:
list($value) = $mysqli->fetch_array;
you can assign directly more variables, not just one and so you can avoid using arrays completely. See the php function list() for details.
This doesn't completely avoid the array but dispenses with it in one line.
function getval($query) {
$mysqli = new mysqli();
$mysqli->connect(HOST, USER, PASS, DB);
return $mysqli->query($query)->fetch_row()[0];
}
First and foremost,
Such a function should support prepared statements
Otherwise it will be horribly insecure.
Also, such a function should never connect on its own, but accept an existing connection variable as a parameter.
Given all the above, only acceptable way to call such a function would be be like
$name = getVal($mysqli, $query, [$param1, $param2]);
allowing $query to contain only placeholders, while the actual data has to be added separately. Any other variant, including all other answers posted here, should never be used.
function getVal($mysqli, $sql, $values = array())
{
$stm = $mysqli->prepare($sql);
if ($values)
{
$types = str_repeat("s", count($values));
$stm->bind_param($types, ...$values);
}
$stm->execute();
$stm->bind_result($ret);
$stm->fetch();
return $ret;
}
Which is used like this
$name = getVal("SELECT name FROM users WHERE id = ?", [$id]);
and it's the only proper and safe way to call such a function, while all other variants lack security and, often, readability.
Try something like this:
$last = $mysqli->query("SELECT max(id) as last FROM table")->fetch_object()->last;
Cheers

Exclude a field from a SELECT * FROM $table

I need to exclude a field 'password' from a SELECT * FROM $table; where $table is a PHP variable.
Only one of the four posible tables has a 'password' field.
Here is what I have:
function myData($table)
{
include "conf.php";
$con = mysqli_connect($host, $user, $password, $db);
$sql = "SELECT * FROM $table;";
$resul = mysqli_query($con, $sql);
return $resul;
}
Any ideas?
EDIT: This is how I treat the data returned:
$resulFields = myFields($table);
$resulData = myData($table);
while ($fields = mysqli_fetch_array($resulFields, MYSQLI_ASSOC)) {
$field = $fields['Field'];
$header .= "<th>$field</th>";
while ($data_array = mysqli_fetch_array($resulData, MYSQLI_ASSOC) ) {
$body .= "<tr id='$data_array[id]'>";
foreach ($data_array as $data){
$body .= "<td>$data</td>";
}
}
}
Sorry if it's a little bit messy, I'm just starting to learn programming.
I understand that you're wanting to have a single PHP function that will return all the results in a given table. Perhaps instead of returning the $resul variable and parsing the data after the return, you should parse it into an associative array prior to returning it. You can try something like this:
function myData($table) {
include "conf.php";
$con = mysqli_connect($host, $user, $password, $db);
$sql = "SELECT * FROM {$table}";
$resul = mysqli_query($con, $sql);
$row = $resul->fetch_assoc();
unset( $row['password'] );
return $resul;
}
Though I feel it's important to note that in the interests of proper coding practices and single responsibility, you should have specific data access functions for each query you wish to run. I don't recommend having a single function that just returns everything from a table. Functions should also be named such that you know what they're doing. "myData" is very non-descriptive and as such a very poor name for a data access function.
Also, if you're going to name a variable $resul, just go ahead and type the "t" and name it $result FFS.
In the foreach loop, get the key and the data from the array. (The current code is getting only the data.)
Inside the foreach loop, do a conditional test on the value of key.
If the value of the key matches "password", then skip over outputting anything for that element of the array. If it doesn't match key, then output it (like the current code is doing.)
Look at the alternative syntax for foreach:
References: http://php.net/manual/en/control-structures.foreach.php
And for simple conditional tests
Reference: http://php.net/manual/en/control-structures.if.php
Consider whether you want to match "password", "PASSWORD", "Password", etc. You might want a case insensitive match.
Maybe you can do something like this:
function myData($table) {
include "conf.php";
$con = mysqli_connect($host, $user, $password, $db);
$sql = "SELECT field1, field2";
if ($table == "TABLE_WITH_PASSWORD") {
$sql.=",password";
}
$sql.=" FROM $table;";
$resul = mysqli_query($con, $sql);
return $resul;
}
Obviously the best bet is to select what you do want:
SELECT id, name, whatever FROM $table
Hopefully I'm not going down the wrong path, but here is one way other than querying for the fields and removing the password:
$columns['tableA'] = array('id', 'name', 'whatever');
$columns['tableB'] = array('id', 'user', 'something');
Then do:
$select = implode(',', $columns[$table]);
$sql = "SELECT $select FROM $table";
IMO i think the simplest way in this case is to use special case for php
function myData($table) {
include "conf.php";
$con = mysqli_connect($host, $user, $password, $db);
if($table == "special_case_table"){
$sql = "SELECT col1, col2, col3 FROM special_case_table;"; //except "password" column
}
else $sql = "SELECT * FROM $table;";
$resul = mysqli_query($con, $sql);
return $resul;
No need more function or go search in INFORMATION_SCHEMA of database to find column password.

Fetch data row by row with Ajax

I want to fetch data from my mySQL db row by row so that I can combine the first column with the second and so on in a list.
I've searched and found solutions but none of them are using PDO.
Here's the php code that I'm using now to give me the first value written to the console with AJAX.
$db = new PDO('mysql:host=XXXXX;dbname=XXXXX;charset=utf8', 'XXXXX',
'XXXXX');
$partyID = ($_POST['paramName']);
$stmt = $db->prepare("SELECT * FROM wapp_Wishes_db WHERE partyID = '$partyID'");
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows[0]);
I've also tried using Fetch_assoc, but as you can see I'm probably using it completely wrong.
Why would you like to combine those rows? Encode them and use the variables in javascript:
$stmt = $db->prepare("SELECT *
FROM wapp_Wishes_db
WHERE partyID = :partyId");
$stmt->bindParam(':partyId', $_POST['paramName'], PDO::PARAM_STR, 12);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
Maybe you can use implode like that :
$result = implode('&',$rows);
echo json_encode($result);
replace '&' by what you want.
More info here on php manual

Accessing a MySQL Link Identifier from within a Function

I'm having some difficulty returning an array out of a while lopp which I have in a function. Here is the code I am using. I am meant to be able to return an array of results from the function which contains the id numbers of pictures associated with a particular user id - in this case I want to print_r the array for the user id of 17. When this code isn't in the function it works, but when I place it in the function, no luck. I presume its related to a mistake I am making in the returning of the array. Your help is greatly appreciated.
function picture($id)
{
$sql = "SELECT * FROM avatar WHERE user_id={$id}";
$result = $database->query($sql);
$results = array();
while ($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}
return $results;
}
$results = picture(17);
print_r($results);
Your function can't access your MySQL link identifier
First of all, you're mixing object-oriented paradigm ($database->query($sql)) with procedural paradigm (mysql_fetch_assoc($result)) which will make your code a nightmare to maintain.
Assuming that $database is a mysql_ link identifier, you'll need to pass it into your function in order to access it there.
function getUserAvatar($database, $id){
$sql = 'SELECT * FROM `avatar` WHERE `user_id`=' . intval($id) . ' LIMIT 1;';
$result = mysql_query($database, $sql);
$row = mysql_fetch_assoc($result);
return $row;
}
$results = picture($database, 17);
Don't just copy-paste that, keep reading!
The above will probably work, but if you're allowing a user to pass that user ID into the function, it's quite possible that they'll be able to find a vulnerability to inject an SQL statement of their choice into your MySQL database.
mysql_ functions are deprecated, so you should ideally stop using them and switch to mysqli or PDO. You'll also want to get an understanding of prepared statements in order to prevent SQL injections. If you can't upgrade, look at the mysql_real_escape_string and intval functions and make sure you sanitize all user inputs before processing them.
The resulting code will look something like this, if you switch to mysqli and prepared statements:
function getUserAvatar($db, $userId) {
$stmt = $db->prepare("SELECT * FROM `avatar` WHERE `user_id`=? LIMIT 1;");
$stmt->bind_param("i", $userId);
$stmt->execute();
$res = $stmt->get_result();
return $res->fetch_assoc();
}
$db = new mysqli("localhost", "user", "password", "database");
$result = getUserAvatar($db, 17);
may be you should try this..
function picture($id)
{
$sql = "SELECT * FROM avatar WHERE user_id={$id}";
$result = $database->query($sql);
$row = mysql_fetch_assoc($result);
return $row;
}
$results = picture(17);
print_r($results);

About the mysql_query -> mysql_fetch_array() procedure

Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}

Categories