Create an array from a mysqli prepared statment - php

I have a simple script that I am trying to understand why it will not work, and how to get exactly what I want.
What I want to get is an array, call it $results and have the data stored as follows
$results ->
$row1 ->
$field1
$field2
$field3
$field4
$field5
$row2 ->
$field1
$field2
$field3
$field4
$field5
etc...
but I cant even get the mysqli to loop out the results at all, here is my code...
require_once ('lib/constants.php');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to Database.');
$query = "SELECT * FROM employees LIMIT 0, 20";
if($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$row = array();
stmt_bind_assoc($stmt, $row);
while($stmt->fetch()) {
var_dump($row);
}
}

Please check mysqli_result::fetch_assoc method on PHP.net for better understanding.
Below is a quick example
require_once ('lib/constants.php');
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die('Error connecting to Database.');
$query = "SELECT * FROM employees LIMIT 0, 20";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['myfield'];
}
/* free result set */
$result->free();
}

You should check mysqli_result:::fetch_all instead of mysqli_result::fetch_assoc
$query = "SELECT * FROM employees LIMIT 0, 20";
if ($result = $mysqli->query($query)) {
$array_assoc = $result->fetch_all();
/* free result set */
$result->close();
}

Related

Why does this function always return true even if it shouldn't?

I have a function that goes through the product database table and if there is a row with supplierid and name that matches the parameters, then it returns true.
But it always returns true even if it shouldn't.
function checkifhoused($productname, $supplier)
{
$db = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM " . TBL_PRODUCTS;
$result = mysqli_query($db, $sql);
while ($row = $result->fetch_assoc()) {
if ($row['supplierid'] == $supplier and $row['name'] == $productname) {
return true;
}
}
return false;
}
First: I can advice you to use PDO extension. It have better variables binding options.
Second: as #pavel & Ro Achterbeg mentioned in theirs comment you need not fetch all rows from DB table, but check only record with needle parameters exists
<?php
define('TBL_PRODUCTS', 'TBL_PRODUCTS');
function checkifhoused($db, $productname, $supplier)
{
$sql="SELECT * FROM ".TBL_PRODUCTS." WHERE name = ? AND supplierid = ? ";
$stmt = $db->prepare($sql);
$result = $stmt->execute([$productname, $supplier]);
return $stmt->rowCount() > 0;
}
var_dump(checkifhoused($pdo, 'productname', 1));
var_dump(checkifhoused($pdo, 'other_productname', 1));
Here you can test PHP & SQL code

php how to print sql values after mysql_fetch_array

i have SQL query :
SELECT countryCode FROM itins_countries WHERE (itinID = 5);
$countriesIndex = mysql_fetch_array($countriesQuery);
now, in another art of my code I would like to run on the "$countriesIndex" and print all the values it contain ("countryCode");
how can i do that?
while($row = mysql_fetch_array($countriesQuery)){
echo $row['column_name'];
///same for other columns
}
you can use the while loop to loop until all the array element has been printed
try this....
echo "<pre>";print_r($countriesIndex);
mysql_connect is deprecated...you can use mysqli_connect.
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($mysqli, "utf8");
$sql = "SELECT countryCode FROM itins_countries WHERE (itinID = 5)";
$result = mysqli_query($mysqli, $sql);
$countries = [];
while($row = $result->fetch_assoc())
{
$users_arr[] = $row;
}
$result->close();
print_r($users_arr);

Passing PHP array as parameter for SQL WHERE clause

Adapting an answer from here to try and pass an array as the parameter for a WHERE clause in MySQL. Syntax seems okay but I'm just getting null back form the corresponding JSON. I think understand what it is supposed to do, but not enough that I can work out where it could be going wrong. The code for the function is;
public function getTheseModulesById($moduleids) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$in = join(',', array_fill(0, count($moduleids), '?'));
$select = "SELECT * FROM modules WHERE id IN ($in)";
$statement = $con->prepare($select);
$statement->bind_param(str_repeat('i', count($moduleids)), ...$moduleids);
$statement->execute();
$result = $statement->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
mysqli_close($con);
return $arr;
}
And the code outwith the function calling it looks like;
$id = $_POST['id'];
$player = $db->getPlayerDetails($id);
if ($player != false) {
$pid = $player["id"];
$moduleids = $db->getModulesByPlayerId($pid); //this one is okay
$modules = $db->getTheseModulesById($moduleids); //problem here
$response["player"]["id"] = $pid;
$response["player"]["fname"] = $player["fname"];
$response["player"]["sname"] = $player["sname"];
$response["modules"] = $modules;
echo json_encode($response);
[EDIT]
I should say, the moduleids are strings.

Flattening a SQL query result for PHP array

I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.

PHP - Test if there's a MySQLi output

I want to have a php script that tests if there's a mysql output, currently I have the following code:
$mysqli = new mysqli('localhost', 'root', NULL, 'forum');
$query = "SELECT id,titel,auteur,datum FROM topics WHERE categorieid=$categorieid ORDER by id DESC";
To test for a result I have no working code, so it wouldn't help posting the rest here
I want an if statement, if the query sends back a result echo this, else echo this
Who can help me with this? Thanks!
Reminder: It has to be MySQLi, using MySQL is 'outdated' as PHP calls it
EDIT:
if ($stmt = $mysqli->prepare($query)) {
$stmt->execute();
$stmt->bind_result($id,$titel,$auteur,$datum);
$stmt->close();
}
$mysqli = new mysqli('localhost', 'root', '', 'forum');
$query = "SELECT id,titel,auteur,datum FROM topics WHERE categorieid='$categorieid' ORDER by id DESC";
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if ($result = $mysqli->query($query)) {
printf("Select returned %d rows.\n", $result->num_rows);
$result->close();
} else {
printf("Select returned no rows.\n");
}
you need to try like
$mysqli = new mysqli('localhost', 'root', '', 'forum');
$query = "SELECT id,titel,auteur,datum FROM topics WHERE categorieid='$categorieid' ORDER by id DESC";
query variable should be quoted.
For more :- http://www.php.net/manual/en/mysqli-stmt.execute.php

Categories