Function argument for mysqli field - php

Need to pass through an argument for column header in to function.
Would like to have ["name"] be an argument in the function so I can pull different fields from sql, Can you please help. Thank you.
Here is the function:
function read_pages_array_2 () {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "ORDER BY id ASC";
$result = mysqli_query ($connection, $query);
confirm_query ($result);
while($result_use = mysqli_fetch_assoc($result)) {
echo $result_use["name"] . "<br/>";
}
}

function read_pages_array_2($columnName) {
global $connection;
$query = "SELECT p.".$columnName." FROM pages p ORDER BY id ASC";
$result = $connection->query($query); // Object Oriented use of connection
confirm_query($result);
while ($result_use = $result->fetch_assoc()) {
echo $result_use[$columnName] . "<br/>";
}
Yes?

OP asked
Looking for ["name"] to be an argument, so I can change when using
function and instead of name, get ["page_id"] or whatever else.
function read_pages_array_2 ($param) {
global $connection;
$query = "SELECT * ";
$query .= "FROM pages ";
$query .= "ORDER BY id ASC";
$result = mysqli_query ($connection, $query);
confirm_query ($result);
while($result_use = mysqli_fetch_assoc($result)) {
echo $result_use[$param] . "<br/>";
}
}
read_pages_array_2("name");
read_pages_array_2("pageID");
Isn't this straight forward?

Related

How do I separate output from database?

I tried to get multiple rows out from my database with PHP but all I get is one line of text like: "8910"
My code is following:
$sql = "SELECT * FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$rows = mysqli_num_rows($sth);
for ($x = 0; $x <= $rows; $x++) {
$sql = "SELECT idPosts FROM posts WHERE idUsers=$id";
if(!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$result = mysqli_fetch_array($sth);
$postId = $result['idPosts'];
echo $postId;
}
And then I edit this: echo $postId." ";
And get a space between the id's like this: 8 9 10.
I tried to do $postIds = explode(" ", $postId);
And then echoing out for example $postIds[0] but I get all the id's once again
Now I do not know what to do so I need help ^^
Replace $postId = $result['idPosts']; with $postId[] = $result['idPosts'];. That way you create an array an you can just access it like $postId[0].
You also forgot to query again.
...
$sql = "SELECT idPosts FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if(!$sth) {
...
Your second query is unnecessary, you already have all the data from your first query. Just replace your code with this:
$sql = "SELECT * FROM posts WHERE idUsers=$id";
$sth = $conn->query($sql);
if (!$sth) {
echo("Error description: " . mysqli_error($conn));
die();
}
$postIds = array();
while ($row = mysqli_fetch_array($sth)) {
$postIds[] = $result['idPosts'];
}
After this loop you will have an array of all the idPosts values. You can then process them as you need to. Or you can process them in the loop:
while ($row = mysqli_fetch_array($sth)) {
$postId = $result['idPosts'];
// code to process postId e.g.
echo "$postId<br/>";
}

Php and MySQL reading data from multiple table

What is wrong with this code. I got 3 tables I’m trying to get data from. A Recipe table, a ingredient table, and a recipeingredient table. The recipeinredient holds the ids for recipe and ingredient for the recipe. So far I can display data from recipe and recipeingredient table. Now I’m trying to get the data from the Ingredient table.
$id = $_GET['id'] ?? ''; //PHP > 7.0
$recipe_id = $id;
$recipe = find_recipe_by_id($id);
$recipeingredient_set = find_all_recipeingredient_by_recipe_id($recipe_id);
while($recipeingredient = mysqli_fetch_assoc($recipeingredient_set)){
$ingredient = find_ingredient_by_id($recipeingredient['ingredient_id']);
echo "<br /> ";
echo $ingredient['name'];
echo "<br /> ";
}
function find_ingredient_by_id($id){
global $db;
$sql = "SELECT * FROM Ingredient ";
$sql .= "WHERE id='" . $id . "'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$ingredient = mysqli_fetch_assoc($result);
return $result; // returns an assoc. array
}
function find_all_recipeingredient_by_recipe_id($recipe_id){
global $db;
$sql = "SELECT * FROM RecipeIngredient ";
$sql .= "WHERE recipe_id='" . $recipe_id . "'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
return $result;
}
you are returning the result and not the array, just update your return line
function find_ingredient_by_id($id){
global $db;
$sql = "SELECT * FROM Ingredient ";
$sql .= "WHERE id='" . $id . "'";
$result = mysqli_query($db, $sql);
confirm_result_set($result);
$ingredient = mysqli_fetch_assoc($result);
return $ingredient; // returns an assoc. array
}
You are returning the resultset return $result; // returns an assoc. array but you should be returning the assoc array $ingredient
function find_ingredient_by_id($id){
global $db;
$sql = "SELECT * FROM Ingredient ";
$sql .= "WHERE id='" . $id . "'";
$result = mysqli_query($db, $sql); //The resultset. This is what you were returning.
confirm_result_set($result);
$ingredient = mysqli_fetch_assoc($result); //An assoc array. What you wanted to return.
return $ingredient; // returns an assoc. array
}

sometimes return the value and somestimes return bool(false)

this one return bool(false)
function authenticate($user, $pass){
$sql = "SELECT * FROM Users ";
$sql .= " WHERE UniqueUser = \"{$user}\" ";
$sql .= " AND HashedPass = \"{$pass}\" ";
$sql .= " LIMIT 1";
$result = mysqli_query($sql);
$result_set = mysqli_fetch_array($result);
return !empty($result_set) ? array_shift($result_set) : false;
}
if searched with any other database columns like firstname,lastname it return
the whole row and everything is going well
function authenticate($user, $pass){
$sql = "SELECT * FROM Users ";
$sql .= " WHERE LastName= \"{$user}\" ";
$sql .= " AND HashedPass = \"{$pass}\" ";
$sql .= " LIMIT 1";
$result = mysqli_query($sql);
$result_set = mysqli_fetch_array($result);
return !empty($result_set) ? array_shift($result_set) : false;
}
why sometimes some columns doesn't work as expected?

Querying a database within a PHP function [duplicate]

This question already has answers here:
mysqli/mysql query inside function not working [duplicate]
(2 answers)
Closed 9 years ago.
I'm trying to load some data from a database using PHP, but for some reason it doesn't work when I put it inside a function. If I try the code without a function, it works fine:
//$dbc connection
$call1 = 0;
$output = '';
$query = "select * from artists order by lname limit $call1, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
However, when I change the code to be inside a function, I don't get anything from the database (or at least it won't return anything):
//$dbc connection
$call1 = 0;
$output = '';
function loadArtists($call){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1);
What am I doing wrong here?
You cannot use $dbc in your function, because it is a global variable.
You can use either
function loadArtists($call){
global $dbc;
...
}
to make $dbc known to loadArtists() or pass it as a second parameter
function loadArtists($dbc, $call){
...
}
and call it as
loadArtists($dbc, $call1);
As I mentioned in one of my comments, using global to fix the scope of your connection is poor practice. The correct way to pass your connection is like so:
$dbc = mysqli_connect("localhost", "my_user", "my_password", "world");
$call1 = 0;
$output = '';
function loadArtists($call, $dbc){
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
}
loadArtists($call1, $dbc);
Declaring your username and password on the same page as the code you're executing every time you want to make a DB connection is bad practice because:
You could potentially have more than one page to edit if you move to a different host or a different environment than the dev environment.
If you declare it outside of the root you can limit access to the DB password from FTP accounts.
I like to use a function for the connection so this way if the connection closes you can reopen it at will (reducing server overhead). Also you don't have to set it as a global var inside the function (not a good idea because of several reasons).
So for those reasons, this connection should be outside (below) the root.
/../safe/connection.php
function openSQL() {
$conn = mysqli('localhost', 'my_user', 'my_password', 'my_db');
return $conn;
}
functions.php
require_once($_SERVER['DOCUMENT_ROOT'].'/../safe/connection.php');
function loadArtists($call){
$dbc = openSQL();
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
mysqli_close($dbc);
return $output;
}
$myOutput = loadArtists(4);
The problem is variable scope. That variable does not exist within your function.
There are three ways to deal with that:
Make it global, that means an outside variable is readible from within a function. (Note that using global variables is often considered a security concern.)
global $dbc;
You can pass that variable into the function as an argument
function loadArtists($connection, $call) { ... }
you can make a class and that class variable will now be useable inside of class functions:
class Artists {
public $dbc;
public function __construct() {
$this->dbc = open_the_db_connection(); //etc?
}
public function loadArtists($call) {
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($this->dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
return $output;
}
}
It looks like a scoping issue to me. The $output you reference in the function isn't the same as the $output you defined outside the function.
You should change your function to the following:
function loadArtists($call){
$output = "";
$query = "select * from artists order by lname limit $call, 15";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$output .= "<ul>";
$output .= "<li>" . $row['name'] . "</li>";
$output .= "</ul>";
}
return $output;
}
$output = loadArtists($call1);

OOPHP select from MySQL

I am wondering how to do the following I want to create a public function that allows me to do selects from MYSQL
Here is the code I have so far but it brings up a if error.
public function select($table,$options,$where,$orderby)
{
$sql = mysql_query("SELECT ".
if($options)
{
$options
}
." FROM ".
$table
if($where)
{
." WHERE ".$where.
}
if ($orderby)
{
." ORDER BY ".$orderby.
}
."") or mysql_error() ;
$row = mysql_fetch_assoc($sql);
$rows[] = $row;
print json_encode($rows);
}
Parse error: syntax error, unexpected T_IF in /home/realcas/public_html/eshop/ecms/system/classes/database.php on line 23
Try
$sql = mysql_query("SELECT ". $options ." FROM ". $table .
($where ? "WHERE " . $where : "") .
($orderby? "ORDER BY ".$orderby : "")) or mysql_error() ;
$row = mysql_fetch_assoc($sql);
$rows[] = $row;
print json_encode($rows);
You cannot have if-statements inside a function call. Build your SQL outside and then pass it directly to mysql_query. Example:
$sql = "SELECT ";
if($options)
$sql .= "FROM " . $table;
if($where)
$sql .= " WHERE " . $where;
if($orderby)
$sql .= " ORDER BY " . $orderby;
$query = mysql_query($sql);
I also assume that you're missing an exit before mysql_error(). As it is now, you wont get any output. Change it to:
mysql_query($sql) or die(mysql_error());
Third, you will only be able to fetch a single row since you only invoke mysql_fetch_assoc once. You should continue iterating over it as long as there are results:
$rows = array();
while($row = mysql_fetch_assoc($query))
$rows[] = $row;
// $rows will now contain all rows returned from your select statement
enhanced way:
public function select($table,$options,$where,$orderby)
{
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
$result= mysql_query($qry) or die(mysql_error());
while(($resultArray[] = mysql_fetch_assoc($result));
return json_encode($resultArray);
}

Categories