fetching option values from mysql - php

I new to php and mysql.
I wrote the function below:
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$funcCat = array();
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
for ($i = 0; $i < count($maincatfunc_query); $i++) {
$funcCat[$i] = '<option value="'.$maincatfunc_sorgu['mainCatID'].'">' . $maincatfunc_sorgu['name'] . '</option>';
}
}
for ($i = 0; $i < count($maincatfunc_query); $i++) {
return $funcCat[$i];
}
}
I want to fetch "all" value from mysql database and fill it in a dropdown. So i wrote a function like this. But it does not work.
And i don't think count() function doesn't really work in this conditions. How can i get the max count of mysql array ?.
or besides can i do this without using a function ?. I've googled it for a long time but i can't find any usefull info.
Thanks !

You should use like below: [returns array]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = array();
while ($row = mysql_fetch_array($query)) {
$arrCat[] = '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}
Or this one [returns string]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}

You should try this,
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
$funcCat .= '<option value="'.$mainCatFunc['mainCatID'].'">' . $mainCatFunc['name'] . '</option>';
}
return $funcCat;
}
Use like this :
$dropDownData = catOption();
put it into HTML
<select><?php echo $dropDownData; ?></select>

Related

join query not working properly

I want to select two table values so I am using join query see below, from this code I stored one session variable like $_SESSION['emp_id'], I want select query like who are in te.emp_id='".$_SESSION['emp_id']."', From this code $count will return 0 but in my database I have one row.
$q = mysql_query("SELECT *
FROM task_employee te
JOIN task t
ON te.emp_id = t.t_assign_to
WHERE t.t_status = '0'
AND t.t_delete_on != '1'
AND te.emp_id = '" . $_SESSION['emp_id'] . "'");
$data = array();
while($r = mysql_fetch_assoc($q))
{
$data[] = $r;
}
$count = sizeof($data);
if($count > 0)
{
$return = array('status'=>'success', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
else
{
$return=array('status'=>'not-found', 'count'=>sizeof($data), 'data'=>$data);
echo json_encode($return);
}
I am writing like this means I can get but using join query that time I can't get values
<?php
$sql = mysql_query("SELECT *
FROM task
WHERE t_delete_on !='1'
AND t_assign_to = '$emp_id'");
for ($i = 1; $row = mysql_fetch_assoc($sql); $i++)
{
$assign_to = $row['t_assign_to'];
$mysql = mysql_query("SELECT *
FROM task_employee
WHERE emp_id = '$assign_to'");
while ($r = mysql_fetch_assoc($mysql))
{
$emp_name = $r['emp_firstname']; // here i got value
}
}
?>

Loop from category to sub category in PHP

We are having a structure like the way you are seeing in below screenshot:
And our database structure looks like this:
Here in database table "PID" is the Parent ID in which 0 = Parent ID. And rest PID is the parent id of same id.
Now we are trying to get all the sub category of "Brand" Or "Footware" so it should show all (sub-sub-category and sub-sub-sub-category) the sub category details under that tree. Can this be done through PHP? any loop or any way?
Thank you!
try this
function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER BY id ASC";
$result=$con->query($sql);
if (mysqli_num_rows($result) > 0)
{
$user_tree_array[] = "<ul>";
while ($row =$result->fetch_object())
{
$user_tree_array[] = "<li>". $row->name."</li>";
$user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
}
$user_tree_array[] = "</ul><br/>";
}
return $user_tree_array;
}
call function here
$res = fetchCategoryTreeList();
foreach ($res as $r)
{
echo $r;
}
Try like this:
<?php
//connect to mysql and select db
$conn = mysqli_connect('localhost', 'rootuser', 'rootpwd','dbname');
if( !empty($conn->connect_errno)) die("Error " . mysqli_error($conn));
//call the recursive function to print category listing
category_tree(0);
//Recursive php function
function category_tree($catid){
global $conn;
$sql = "select * from category where pid ='".$catid."'";
$result = $conn->query($sql);
while($row = mysqli_fetch_object($result)):
$i = 0;
if ($i == 0) echo '<ul>';
echo '<li>' . $row->category;
category_tree($row->id);
echo '</li>';
$i++;
if ($i > 0) echo '</ul>';
endwhile;
}
//close the connection
mysqli_close($conn);
?>
Hope this will help.
I used this function in my project, it is a recursive function.
/**** GET ALL CATEGORIES FUNCTION *******/
function categoryChild($id, $spacing = '') {
$s = "SELECT * FROM category WHERE parent_cat_id = $id ";
$r = mysql_query($s);
$children = array();
if(mysql_num_rows($r) > 0) {
while($row = mysql_fetch_array($r)) {
$children[$row['category_id']]['category_name'] = $spacing.$row['category_name'];
$children[$row['category_id']]['id'] = $row['category_id'];
$children[$row['category_id']]['child'] = categoryChild($row['category_id'], $spacing . ' ');
}
}
return $children;
}
> /************ GET ALL CATEGORIES FUNCTION****************/
$allcategory = categoryChild(0);
print_r($allcategory);

Why can't I create a dropdown list with variables?

I'm trying to create a dropdown list with all the values that i have inside my table, but I can't do it, the select box stay blank.
My PHP code, I'm calling a function
Job category
<select>
<?php
function category($category_id, $category_name){
echo "<option value='".$category_name."'>".$category_name."</option>";
}
?>
</select>
And my function
function selectcategory(){
connect();
$category = ("SELECT * FROM job_categories");
$val = DB_array($category, 'a+');
$ii = count($val);
$ii = $ii - 1;
for ($i = 0; $i <= $ii; $i++) {
$category_id = $val[$i]['category_id'];
$category_name = $val[$i]['category_name'];
category($category_id, $category_name);
}
}
Assuming the flow of your code , that 2nd part executes first , i.e. connection is made , data is fetched and you are calling category() , it will execute
function category($category_id, $category_name){
echo "<option value='".$category_name."'>".$category_name."</option>";
}
$ii times and you are returning to the calling function .
So that's why < select > does not populate the data because it is interpreted after running the above code.
<select>
<?php
$result = category($category_id, $category_name);
foreach($result as $key => $value){
echo "<option value='".$key."'>".$value."</option>";
}
?>
</select>
$sql = mysql_query("SELECT * FROM job_categories");
$result = mysql_db_query($dbname, $sql) or die("Failed Query of " . $sql);
while ($row = mysql_fetch_row($result)){
echo "<option value='".$row["category_id"]."'>".$row["category_name"]."</option>"; // the value should be id
}

mysqli_fetch_array reading result as null?

Any idea why this is showing a result of null? I'm guessing it has to do with where I put $link before I did the query, but it has to be done that way, correct?
function getcatposts($cat_id) {
$qc = #mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = #mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
Updated code:
function getcatposts($cat_id) {
$link = mysqli_connect("localhost", "lunar_lunar", "", "lunar_users");
$qc = mysqli_query($link, "SELECT * FROM topics WHERE topic_cat='$cat_id'");
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
}
echo $cat_name;
echo '<br />';
echo $topic_title;
echo '<br />';
echo $topic_id;
}
New issue is that its displaying like this:
http://gyazo.com/43e8a91b9e0cf4f5e413536907891dcf.png
When the DB looks like this:
http://gyazo.com/1ead8bd0f150838dae3ee4a476419679.png
It should be displaying all three of them and this is a function meaning it will keep redoing all the code until it can't query anymore data. Any ideas?
The problem here is that you're trying to echo the values outside your loop. The variables inside the loop will get overwritten on each iteration and at the end of looping, the variable will hold the value of the last iteration.
If you want to display all the values, move the echo statement inside your loop, like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title = $row['topic_subject'];
$topic_id = $row['topic_id'];
echo $topic_title.'<br/>';
echo $topic_id.'<br/>';
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name = $row2['cat_name'];
echo $cat_name.'<br/>';
}
If you care about the order, you could store the titles, ids and cat_names in arrays like so:
while($row = mysqli_fetch_array($qc))
{
$topic_title[] =$row['topic_subject'];
$topic_id[] = $row['topic_id'];
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2))
{
$cat_name[] =$row2['cat_name'];
}
And then loop through them:
for ($i=0; $i < count($topic_id); $i++) {
if( isset($topic_id[$i], $topic_title[$i], $cat_name[$i]) )
{
echo $cat_name[$i].'<br/>';
echo $topic_title[$i].'<br/>';
echo $topic_id[$i].'<br/>';
}
}
Your function displays only one result because your echo is outside the while loop...
Put the Echo statements inside the loop, or you will print only the last result!
while($row = mysqli_fetch_array($qc)) {
$topic_title=$row['topic_subject'];
$topic_id=$row['topic_id'];
echo $topic_title;
echo '<br />';
echo $topic_id;
}
$qc2 = mysqli_query($link, "SELECT * FROM categories WHERE cat_id='$cat_id'");
while($row2 = mysqli_fetch_array($qc2)) {
$cat_name=$row2['cat_name'];
echo $cat_name;
echo '<br />';
}

Fetch all rows for each row in a database

I have a database with list of members. I execute a certain query it selects all members satisfying a condition. Then for each member in resultset, I want to send the details of all members generated in output and continue the loop until end of resultset. My current SQL query is:
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($r = mysql_fetch_array($result,MYSQL_ASSOC))
{
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $row['latitude'] . "," . $row['longitude'];
$i = $i + 1;
}
**$registration_id = $r['user_id'];**
}
}
This does not give me an intended result? Any loopholes or bugs in this?
The first while fetches the entire row as an array. The second while made no sense.
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($r = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $r['latitude'] . "," . $r['longitude'];
$i = $i + 1;
//Send notification to that member
}
}
Try without first WHILE
if( $result || mysql_num_rows($result) != 0)
{
$string = "result";
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$string .= "," . $row['latitude'] . "," . $row['longitude'];
$i = $i + 1;
}
//Send notification to that member
}
Try the foreach PHP loop
Like This;
Query the database and build an array of the members given the specific conditions and build the members array like this
$members = array(); // Intialize Empty Array
$sql = "SELECT member_name FROM .... WHERE ... "; // Ensure you're selecting one field here
while($result = $mysql_fetch_assoc(mysql_query($sql)))
{
$members[]=$result['member_name'];//This is the members array we're adding members to
}
//Get Members Array Count
$member_count = count($members);
//Check whether members array is more than 0
if($member_count != 0)
{
//Do for each loop to select profiles for each member in our array
foreach($members as $key)
{
$sql = " SELECT email,number,imei,device,latitude,longitude,userID FROM ... WHERE member_name LIKE '$key' ";
while($result = $mysql_fetch_assoc(mysql_query($sql)))
{
//print results here
.
.
.
}
}
}

Categories