done - php sql use callback - php

EDIT:
PROBLEM IS FOLLOWING:
$pageTitle cannot be used outside the function.
Here is what I got so far:
function getMetaData($table, $rows){
echo $table;
echo $rows;
$selectTitle = "select * from $table";
$getTitle = mysql_query($selectTitle);
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
}
getMetaData('metadata', 'Pagetitle');
My output
<?php echo $pageTitle ?>
--> this is undefined
Thank you

Your function does not return any value nor does it prints any value. based on your EDIT use
global $pageTitle;
at the beginning of your function and before using the variable.

You should initialize the variable $pageTitle first like,
function getMetaData($table, $rows){
echo $table;
echo $rows;
$selectTitle = "select * from $table";
$getTitle = mysql_query($selectTitle);
$pageTitle='';
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
return $pageTitle; // returning the variable will work here
}
echo getMetaData('metadata', 'Pagetitle');

Just TRY with mysql_free_result() like
$selectTitle = "SELECT * FROM '".$table."'";
$getTitle = mysql_query($selectTitle);
$pageTitle = '';
while ($showTitle = mysql_fetch_assoc($getTitle)){
$pageTitle = $showTitle[$rows];
}
return $pageTitle; //Return even the pageTitle.
mysql_free_result() will free all memory associated with the result.
And as per your EDIT try like :
$pageTitle = getMetaData('metadata', 'Pagetitle');
echo $pageTitle;

Related

Unable to return desired value, query and loop keeps returning i

Hello I was trying to put the results of the query to an array but it's not working intead it only displays i
<?php
$sqlo = mysqli_query($conn, "SELECT * FROM users");
$i=1;
while ($h=mysqli_fetch_assoc($sqlo)) {
echo "<br>counter[i] : ".$counter[$i] = $h['username'];
echo "<br>i++ : ".$i++;
}
?>
As Barmar suggestion is recommended separating the assignment from echo.
Try this code:
<?php
$sqlo = mysqli_query($conn, "SELECT * FROM users");
$i=1;
$counter = [];
while ($h=mysqli_fetch_assoc($sqlo)) {
$counter[$i] = $h['username']; //if you need to store username inside an array
echo "<br>counter[i] : ".$counter[$i];
echo "<br>i++ : ".$i++;
}
create array variable before loop.
$i=1;
$counter[];
while ($h=mysqli_fetch_assoc($sqlo)) {
echo "<br>counter[i] : ".$counter[$i] = $h['username'];
e
echo "<br>i++ : ".$i++;
}

Get variables work beyond curly brackets

In this code I have defined variable id now if I will use $id outside curly brackets I will get error undefined variable for $id. Is there any way in which I can use variables outside brackets.
<?php
if (isset($_GET['username'])) {
$check = $db->prepare("SELECT id, email, phone, FROM members WHERE username=:username");
$check->execute(array(':username'=>$username));
$get = $check->fetch(PDO::FETCH_ASSOC);
$id = $get['id'];
$email = $get['email'];
}
else {
// error
}
$posts =$db->prepare("SELECT * FROM posts WHERE id=:id");
$posts->execute(array(':id'=>$id));
$row=$posts->fetch(PDO::FETCH_ASSOC));
$title = $row['title'];
$body = $row['body'];
?>
<?php
$id=""; //initialize a variable with blank value
if (isset($_GET['username'])) {
// query to get data
$id = $_GET['id'];
}
else {
// error
}
?>
Try this:
You can define your variable id like global $id; define immediate after php tag started .
<?php
global $id;
if (isset($_GET['username'])) {
// query to get data
$id = $get['id'];
}
else {
// error
}
?>

Passing retrieved database records to a php file

system/article.php
<?php
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["articleTitle"];
echo $row["articleSummary"];
echo $row["articleContent"];
}
} else {
echo "0 results";
}
include 'template/homepage.php';
retrieves articles from the article table.
I have included the homepage.php which is supposed to act as a template.
template/homepage.php
<?php include 'template/common/header.php'; ?>
<h1>Article Title here</h1>
<p>articleSummary</p>
<?php include 'template/common/footer.php'; ?>
How do I now pass the retrieved data to the homepage.php to display it on the browser ?
Edit
smarber pointed me to
In the first file:
global $variable;
$variable = "apple";
include('second.php');
In the second file:
echo $variable;
which works. But how do I implement the same with my problem up top?
You may do that via GET, Session or Post; But why don't you simply and efficiently define a function and pass those variables to it, just for example:
function displayArticle($title, $summary, $content) {
displayHeader(); // maybe some concepts you've used in template/common/header.php
echo "<h1>$title</h1><p>$summary</p><div>$content</div>";
displayFooter(); // again, what you've provided in footer.php
}
Well then, you may do the following:
change the template/homepage.php file to:
<?php
include 'template/common/header.php';
echo "<h1>$articleName</h1>";
echo "<p>$articleSummary</p>";
include 'template/common/footer.php';
?>
and change the system/article.php to:
<?php
global $articleName;
global $articleSummary;
global $articleContents;
$sql = "SELECT articleTitle, articleSummary, articleContent FROM articles";
$result = $dbconnect->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$articleName = $row["articleTitle"];
$articleSummary = $row["articleSummary"];
$articleContents = $row["articleContent"];
include 'template/homepage.php';
}
} else {
echo "0 results";
}
However, It's so better to create a cleaner and more reusable code using some facilities you have in the programming language, like using functions and classes :)

How to create a PHP function that contain a MySQL query?

Hello at the moment I'm using a PHP file called select_Type.php that contain a MySQL query to create a <select></select> Box into HTML. I'm using include_once to link my admin.php and ./Includes/select_Type.php. I already created a file called ./Includes/functions.php where all my querys should be set in PHP functions.
I would like to learn more about functions.
Admin page admin.php where the <select></select> is :
<?php
session_start();
include_once './Includes/functions.php';
CheckLogIn('Superadmin');
SelectType();
//require_once './Includes/select_Type.php';
require_once './Includes/register.php';
?>
select_type.php :
<?php
require_once 'functions.php';
$querySQL = "SELECT * FROM tbltype";
$queryResult = GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)){
$dataArrayType[] = $row;
}
?>
What I tried:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
What am I doing wrong ?
Thanks in advance :)
Thank you all especially Déjà vu !!!!!
You were all very helpfull.
The problem was, how most of you told me: I didn't returned the value.
Before:
<?php
function SelectType() {
GLOBAL $_POST;
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
}
?>
Now:
I deleted the GLOBAL $_POST becauce $_POST is already GLOBAL.(Thanks to ɴ ᴀ ᴛ ʜ)
<?php
function SelectType() {
$querySQL = "SELECT * FROM tblType";
$queryResult=GetQuery($querySQL);
while ($row = mysqli_fetch_assoc($queryResult)) {
$dataArrayType[] = $row;
}
return $dataArrayType;
}
?>
admin.php
I put my function SelectType() in my foreach. Et voila!
<select type="text" id="register_type" name="register_type" required>
<?php
foreach (SelectType() as $row) {
echo "<option value='" . $row['idType'] . "'>" . $row['dtType'] . '</option>';
}
?>
</select>
You can use this:
function sel($table,$field="*", $condition="1",$sort="" ){
if($sort!='') $sort="order by $sort ";
//echo "select $field from $table where $condition $sort ";
$sel_query=mysql_query("select $field from $table where $condition $sort ");
//$sel_result=array();
while($temp_res=#mysql_fetch_array($sel_query))
{
$sel_result[]=$temp_res;
}
return isset($sel_result)?$sel_result: 0;
}
And get result:
$temp_res=sel("post","*"," userid ='".$frnd['friend']."' ORDER BY id DESC");
if($temp_res)foreach($temp_res as $row){
echo $row['content'];
}

Not able to echo the variable which is fetched in a function

I got two files name func.inc.php and profile.php
I'm trying to fetch the data from the mysql by creating a function get_data($id) in func.inc.php and display in the profile page(profile.php).But the data is not displaying.
<-- func.inc.php file -->
<?php session_start();
function get_data($id){
$query_in="SELECT * FROM user WHERE id ='$id'";
$query=mysql_query($query_in);
while($row=mysql_fetch_assoc($query)){
$name=$row['name'];
$book=$row['book'];
$mobile=$row['mobile'];
$computer=$row['computer'];
}
}
?>
<-- profile.php -->
<?
include'func.inc.php';
echo "Name: ".$name;
echo "Book: ".$book;?>
The function should return some value then only the values from the function will be got
function get_data($id){
$query_in= sprintf("SELECT * FROM user WHERE id ='%d'", mysql_real_escape_string($id));
$query=mysql_query($query_in);
$result = array();
while($row=mysql_fetch_assoc($query)){
$result[]['name'] = $row['name'];
}
return $result;
}
<-- profile.php -->
$values = get_data($id);
print_R($values);
You should pass the id from the function call that is: here you should call like this:
$values = get_data($id);
while($row=mysql_fetch_array($values)){
echo $name=$row['name']."<br>";
echo $book=$row['book']."<br>";
echo $mobile=$row['mobile']."<br>";
echo $computer=$row['computer']."<br>";
}
in func.inc.php use this code:
function get_data($id){
$query_in="SELECT * FROM user WHERE id ='$id'";
$query=mysql_query($query_in);
return $query;
}

Categories