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

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'];
}

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++;
}

Comparing stored data in a column to an existing value

I have a column called favid. I am trying to pull and compare the data in that column to an existing value:
<?php $query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid=$favid");
while ($row = mysql_fetch_assoc($query)) {
echo $row['favid']; };?>
I also have an existing value:
$x
But when I do something like this it doesn't work:
<?php if($row['favid'] == $x){?>
Do this...
<?php } else { ?>
Do nothing...
<?php}?>
I realize the data in the column somehow isn't pulled out. What should be done for this to work?
Try this, I assume you already connected to DB.
<?php
$x = 1;
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='$favid'") or die(mysql_error());
if (mysql_num_rows($query) > 0)
{
while ($row = mysql_fetch_assoc($query))
{
if ($row["existing_column_name"] == $x)
{
echo "Yes";
} else
{
echo "No";
}
}
} else
{
echo "Nothing was found";
}
?>
<?php
$x = 100500; // integer for example
$CID = mysql_connect("host","user","pass") or die(mysql_error());
mysql_select_db("db_name");
$query = mysql_query("SELECT * FROM ajaxfavourites WHERE favid='{$favid}'", $CID);
while ($row = mysql_fetch_assoc($query)) {
if (intval($row["some_existing_column_name"])==$x){
print "Is equals!";
} else {
print "Is different!";
}
}
?>
Please be informed that mysql_connect and other functions with the prefix of mysql_ is deprecated and can be removed in the next versions of PHP.

non-oop way to display records or fields - mysqli

I've been using mysql and it did what I want, but as my project is getting larger, I decided to opt for mysqli.
I looked at the tutorial at enter link description here which was really straight forward up until the point where I want to display some data
stored procedure (connect.php)
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $con;
// Try and connect to the database, if a connection has not been established yet
if(!isset($con)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('config.ini');
$con = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if( $con === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $con;
}
function db_query($query) {
// Connect to the database
$con = db_connect();
// Query the database
$result = mysqli_query( $con,$query);
return $result;
}
function db_error() {
$con = db_connect();
return mysqli_error($con);
}
function db_select($query) {
$rows = array();
$result = db_query($query);
// If query failed, return `false`
if($result === false) {
return false;
}
// If query was successful, retrieve all the rows into an array
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
function db_quote($value) {
$con = db_connect();
return "'" . mysqli_real_escape_string($con,$value) . "'";
}
?>
php/html
<div class="grid_4">
<div class="left-1">
<h2 class="top-1 p3">Find a property</h2>
<form id="form-1" method="post" class="form-1 bot-1" action="prop_result.php">
<div class="select-1">
<label>Select Area</label>
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}else
{
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}}
?>
</select>
</div>
What I don't understand is how to use the stored procedure in a while loop so it will output the data in the fields ID and Area so my select box and any other input can be properly populated based on the query
current
I've tried different ways :
<?php
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
while($rows=mysqli_fetch_assoc($result))
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
$rows = db_select("SELECT id,city_id,area FROM area");
if($rows === false) {
$error = db_error();
}
{
?>
<option value=""><?php $rows['
area'];?></option>
<?php
}
?>
and
<?php
$rows = db_select("SELECT area_id from property");
if($rows === false) {
$error = db_error();
}
{
echo "<option value='".$rows['id']."'>".$rows[$col4]."</option>";
}
?>
None of these output any data. Echoing $rows gives no data. I don't know what the logic is for using the stored procedure to display the output.
Any help would be appreciated, if any other information is required to assist in resolving this issue, please let me know.
Awesome to hear that the data is returning. Try this out for size...
foreach($rows as $key => $value){
foreach($value as $k => $v){
if($k == 'id'){
$newID = $v;
}
if($k == 'type'){
$newType = $v
}
}
echo "<option value='".$newID."'>".$newType."</option>";
}
with this you should be able to make it work for you liking.
Edit: Didnt see the additional arrays until later...the nested loop should suite you better.
Siniseus way works but its too much code for a simple task. I did work with it to finally come to this
<select name="field4" id="field4" >
<?php
$rows = db_select("SELECT id, city_id,area FROM area");
foreach($rows as $row){
echo "<option value='".$row['id']."'>".$row['area']."</option>";
}
?>
</select>
Simple, clean and really straight forward without too many variables.
$rows = db_select ("Select Query")foreach($rows as $row){
do this
}

Check if row in table is 'equal' to other row

I have the following code to check if a row exists in MySQL:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT 1 FROM files WHERE id='$code' LIMIT 1");
if (mysql_fetch_row($result)) {
echo 'Exists';
} else {
echo 'Does not exist';
}
}
?>
This works fine. But I need to change it a bit. I have the following fields:
id, title, url, type. When someone uses the code above ^ to check if a row exists, I need a variable to get the url from the same row, so I can redirect the user to there.
Do you have any idea how I can do that?
Thanks in advance! :)
Try this:
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT * FROM files WHERE id=" . $code . " LIMIT 1");
if (mysql_num_rows($result) > 0) {
while($rows = mysql_fetch_array($result)) {
echo 'Exists';
$url = $rows['url'];
}
} else {
echo 'Does not exist';
}
}
?>
It is quite simple. I think you don't show any effort to find the solution by yourself.
<?php
if (!empty($_POST)) {
$code = $_POST['code'];
mysql_connect("$dbhost","$dbuser","$dbpass");
mysql_select_db("$dbname");
$result = mysql_query("SELECT url FROM files WHERE id='$code' LIMIT 1");
if ($result) {
$url = mysql_fetch_row($resultado);
} else {
echo 'Does not exist';
}
}
<?php
$sql_query = "SELECT * FROM test WHERE userid ='$userid'";
$result1 =mysql_query($sql_query);
if(mysql_num_rows($result1)>0){
while($post = mysql_fetch_array($result1))
{
$url = $post['url'];
}
}
?>
If mysql_num_rows($result1)>0 it means row is existed fir the given user id

Array not displaying, Notice: array to string conversion

I am attempting to display the contents of an array. I have a SELECT query that transfers two rows from the data base with a WHERE statement;
<?php
session_start();
include 'connection.php';
$inspectit = array();
$update1 = $_POST['inspect'];
$query1 = "SELECT title, reason FROM daysoff WHERE DATE(start) = '$update1' AND gighold = 1";
$day = mysql_query($query1);
while($requesting = mysql_fetch_array($day)) {
$inspectit[] = $requesting;
}
$_SESSION['inspect'] = $inspectit;
header('Location: '. $_SERVER['HTTP_REFERER']) ;
?>
I place the session variable into a new variable,$inspect, defined on a different page. I then try to display the array using;
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect == true) {
echo " </br>Name: </br><a> ". implode($inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
If i var_dump($inspect) all the expected data is there, but it looks like an array holding another array. If i execute code as shown above, this gives a notice of array to string conversion. Where am i going wrong?
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect) {
echo " </br>Name: </br><a> ". implode($inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
You are adding an array of query result into an array. try to change:
from:
while($requesting = mysql_fetch_array($day)) {
$inspectit[] = $requesting;
}
to:
$inspectit = mysql_fetch_array($day);
$_SESSION['inspect'] is an array, so you can used check like
$inspect = $_SESSION['inspect'];
if(count($inspect)>0) {
instead of
if($inspect == true) {
try
<?php
session_start();
$inspect = $_SESSION['inspect'];
if($inspect) {
echo " </br>Name: </br><a> ". implode("-",$inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
or you can use empty() function too like
<?php
session_start();
$inspect = $_SESSION['inspect'];
if(!empty($inspect)) {
echo " </br>Name: </br><a> ". implode("-",$inspect) ."</a></br></br>";
unset ($_SESSION['inspect']);
}
?>
With $inspectit = array(); you are setting $inspectit to an array, then you are trying to set the string (or non-array) $_SESSION['inspect'] to equal that array. You can iterate multiple $_SESSION variables to each iteration of $inspectit as follows:
$n=0;
while($requesting = mysql_fetch_array($day)) {
$_SESSION['inspect'+$n] = $requesting;
$n++;
}
$_SESSION['inpect_count']=$n;
Thus you will know how many variables you setup with the $_SESSION['inpect_count']
I tried all above methods to no avail. I did however get it to work by doing;
<?php
session_start();
include 'connection.php';
$inspectname = array();
$inspectreason = array();
$update1 = $_POST['inspect'];
$query1 = "SELECT title, reason FROM daysoff WHERE DATE(start) = '$update1' AND gighold = 1";
$day = mysql_query($query1);
while($requesting = mysql_fetch_array($day)) {
$inspectname[] = $requesting['title'];
$inspectreason[] = $requesting['reason'];
}
$_SESSION['inspectname'] = $inspectname;
$_SESSION['inspectreason'] = $inspectreason;
header('Location: '. $_SERVER['HTTP_REFERER']) ;
?>
then to call and display the arrays;
<?php
if($inspectname == true) {
$size = sizeof($inspectname) - 1;
for($count = 0; $count <= $size; $count++){
echo " </br>Name: </br><a> ". $inspectname[$count] ."</a>";
echo " </br>Details: </br><a> ". $inspectreason[$count] ."</a></br></br>";
unset ($_SESSION['inspectname']);
unset ($_SESSION['inspectreason']);}
}
?>

Categories