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
}
Related
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/>";
}
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?
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?
function getDepartmentAndCondition($dep, $userid, $cond) {
$result = mysql_query("SELECT * FROM department WHERE ID='$dep'");
while($row = mysql_fetch_array($result))
{
$DepConInfo['Department'] = $row['Department'];
}
$userName = mysql_query("SELECT * FROM users WHERE FacebookID = '$userid'") or die ("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row = mysql_fetch_array($username)) {
$DepConInfo['Name'] = $row['name'];
}
$result2 = mysql_query("SELECT * FROM condition WHERE ID= '$cond' ")
or die("<hr>error in SQL query: " . mysql_error() . "<hr>");
while($row2 = mysql_fetch_array($result2))
{
$DepConInfo['Condition'] = $row2['Condition'];
}
return $DepConInfo;
}
$dep, $userid, and $cond are all ints. the first one $DepConInfo['Department'] is returning the right string, but the other two fail with the error
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in ...
ok I rewrote the function
function getCondition($cond) {
$query = "SELECT * FROM condition WHERE ID = '$cond' ";
$sql = mysql_query($query);
if (!$sql) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while($row2 = mysql_fetch_array($sql))
{
$condition = $row2['Name'];
}
return $condition;
}
but I'm still getting an error:
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition WHERE id = '1'' at line 1 Whole query: SELECT * FROM condition WHERE ID = '1'
the table "condition" has two columns "ID" and "Name".
while($row = mysql_fetch_array($username)) {
PHP is case-sensitive: you have $username with wrong caps - should be $userName
Additionally, based on your naming convention in the first and third queries
$DepConInfo['Name'] = $row['name'];
is probably incorrect and should be capitalized as $row['Name']
function getDepartment($dep) {
$sql = "SELECT * FROM department WHERE ID = '$dep'";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$department = $row['Department'];
}
return $department;
}
function getName($userid) {
$sql = "SELECT * FROM users WHERE FacebookID = '$userid'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$user_name = $row['Name'];
}
return $username;
}
function getCondition($cond) {
$sql = "SELECT * FROM condition WHERE id = '$cond'";
$result = mysql_query($sql);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
$row = mysql_fetch_row($result);
$condition = $row['Condition'];
}
return $condition;
}
$department = getDepartment($dep);
$username = getName($userid);
$condition = getCondition($cond);
I'm writing this from my head so I did not test it, but it should work or at least get you on your way. If not let me know. Mind capitalization using caps in your dbase table and column names can make things more confusing. Use $sql to store your query, use $result to store the result. This is more descriptive. Good luck!
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);
}