I’m trying to filter the second drop box off the first one. The first one $box1 works fine. However I can’t get $box2 to build off the first. If I change
SELECT Site FROM companiesandsitessql WHERE Company ='$box1'");
to
SELECT Site FROM companiesandsitessql WHERE Company =”CompanyA);
it then pulls all the sites for CompanyA in the second box. I’ve tried many variations of $box1 but I must be missing something. Any ideas a appreciated.
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$con = mysql_connect($dbhost, $dbuser);
{
$box1 = array();
mysql_select_db('escalations');
$result = mysql_query("SELECT distinct Company FROM companiesandsitessql");
while($row = mysql_fetch_array($result)) { $box1[] = $row; }
}
/* Generate select box contents */
$out1 = '<select name="box1">';
$out1 .= '<option>Select Company</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$out1 .= '<option value="'.$v['Company'].'">'.$v['Company'].'</option>';
}
}
$out1 .= '</select>';
/* Output */
echo $out1;
{
$box2 = array();
mysql_select_db('escalations');
$result2 = mysql_query("SELECT Site FROM companiesandsitessql WHERE Company ='$box1'");
while($row2 = mysql_fetch_assoc($result2)) { $box2[] = $row2; }
}
/* Generate select box contents */
$out2 = '<select name="box2">';
$out2 .= '<option>Site list</option>';
if (!empty($box2)) {
foreach ($box2 as $k1 => $v) {
$out2 .= '<option value="'.$v['Site'].'">'.$v['Site'].'</option>';
}
}
$out2 .= '</select>';
/* Output */
echo $out2;
?>
Figured it out, here’s the code.
***File new.php***
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$con = mysql_connect($dbhost, $dbuser);
?>
<html>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function autoSubmit() {
$.post('dropoutput.php', { name: box1form.CompanyName.value},
function (output) {
$('#info').html(output).show();
});
}
</script>
<body>
<form name="box1form" action="insert.php" method="post">
<?php
{
$box1 = array();
mysql_select_db('escalations');
$result = mysql_query("SELECT distinct Company FROM companiesandsitessql ORDER BY Company ASC");
while($row = mysql_fetch_array($result)) { $box1[] = $row; }
}
/* Generate select box contents */
$CompanyName = '<select name="CompanyName" onchange="autoSubmit()">';
$CompanyName .= '<option selected="selected">Select Company</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$CompanyName .= '<option value="'.$v['Company'].'">'.$v['Company'].'</option>';
}
}
$CompanyName .= '</select>';
/* Output */
echo $CompanyName;
?>
<div id="info"></div><input name="send" type="submit" value="submit"><br>
</form>
</body>
</html>
***file dropoutput.php***
<?php
mysql_connect("localhost", "root", "") or die (mysql_error ());
$name = mysql_real_escape_string($_POST['name']);
{
$box2 = array();
mysql_select_db('escalations');
$result2 = mysql_query("SELECT Site FROM companiesandsitessql WHERE Company ='$name' ORDER BY Site ASC");
while($row2 = mysql_fetch_assoc($result2)) { $box2[] = $row2; }
}
/* Generate select box contents */
$S = '<select name="SiteOptions[]" multiple="multiple">';
$S .= '<option>Site list</option>';
if (!empty($box2)) {
foreach ($box2 as $k1 => $v) {
$S .= '<option value="'.$v['Site'].'">'.$v['Site'].'</option>';
}
}
$S .= '</select>';
/* Output */
echo $S;
?>
***file insert.php...
<?php
$dbhost = 'localhost';
$dbname = 'escalations';
$dbuser = 'root';
$dbpass = '';
$con = mysql_connect($dbhost, $dbuser);
if($con == FALSE)
{
echo 'Cannot connect to database' . mysql_error();
}
else
{
echo " Connected to database: ";
}
$Site = implode(', ', $_POST['SiteOptions']);
mysql_select_db("escalations", $con);
$sql="INSERT INTO escalationtrackersql (CompanyName, Site)
VALUES
('$_POST[CompanyName]', '$Site')";
echo "Added $_POST[CompanyName] ";
print $Site;
if (!mysql_query($sql, $con))
{
die('Error: ' . mysql_error());
}
echo " : Escalation request successfully entered.";
mysql_close($con)
?>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
</head>
<body bgcolor="#C0C0C0">
<p> </p>
<p><a href="new.php">Return to the
escalation request form</a>.</p>
</html>
Related
How to output the red color level on each member's name like the following screenshot :
Here is the demo webpage URL : http://client.bfm.expert/test_UnilevelBonus.php
Here is the code :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
//Use the following function to get the data of downlines
function getChildren($parent) {
$servername = "11";
$username = "11";
$password = "11";
$dbname = "11";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT user_id, first_name, sponsor_id FROM tbl_user_master WHERE sponsor_id = $parent";
$result = $conn->query($query);
$children = array();
$i = 0;
$result = $conn->query($query) or die($conn->error);
while($row = $result->fetch_assoc()) {
$children[$i] = array();
$children[$i]['name'] = $row['first_name'];
$children[$i]['children'] = getChildren($row['user_id']);
$i++;
}
return $children;
$conn->close();
}
//enter sponsor_id here, change 151 to 145 has a lot of downlines to test
$finalResult = getChildren(145);
//display all downlines of the sponsor
function printList($array = null) {
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo $item['name'];
echo " - level : ";
if (count($item['children'])) {
printList($item['children']);
}
echo "</li>";
}
echo "</ul>";
}
}
printList($finalResult);
?>
You need to pass level into 'printList' function and increment it after.
function printList($array = null, $level = 1) {
if (count($array)) {
echo "<ul>";
foreach ($array as $item) {
echo "<li>";
echo $item['name'];
echo " - level : " . $level;
if (count($item['children'])) {
printList($item['children'], $level+1);
}
echo "</li>";
}
echo "</ul>";
}
}
printList($finalResult, 1);
I'm creating a search bar feature on my website where the user can search for users using a name.The search result may come up with multiple users with similar names (ex. if I search "Jenna", my database may have multiple users with the name "Jenna" so multiple results will show).I want the user to be able to click on one of the profiles and see that specific "Jenna's" user profile. Kind of like Twitter, where I can search for accounts and view different profiles. Right now I have code that returns the search and also makes the search result a clickable link. However, when I try to save the user id, it only saves the latest user id.
home.php (where the search bar for users is0
<form method="GET" action="search.php" id="searchform">
Search for users:
<input type="text" name="search_user" placeholder="Enter username">
<input type="submit" name="submit" value="Search">
</form>
search.php (prints out the users with the name that the user is searching for)
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
}
user_profiles.php (supposed to be where a specific user's profile is shown, based on the link the user clicks with the specific userID)
session_start();
$userID=$_SESSION['user'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
I get where my mistake is, the while loop in search.php will only save the latest userID so the link will always take me to the user profile with that useriD. I'm just not sure how to implement it so that when the user views the list of profiles, the link they click will take them to a specific profile based on the user id.
You need to do changes in search and user.php files :
Search.php :
<?php
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link, "GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
?>
<a href="user_profiles.php?id=<?php echo $id; ?>" >
<?php echo $row['username']; ?>
</a>
<?php
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
header("Location: user_profiles.php");
}
}
User_profile.php:
$userid = $_GET['id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query = "SELECT * FROM dataTable WHERE user_id='$userid'";
$results = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output = $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
$output = $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . " hrs" . "<br>" . "<br>";
$output = $row["date_"];
echo "Date: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
echo '</div>';
}
Very first thing, you are saving multiple user ids to a string.
Another thing, you are saving it in while loop.
Therefore, latest value updates old value.
In your case, it will always save the last value. That is prime issue.
You can take array of user ids and save them in it.
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
And in your user_profiles.php, loop over the array or use MySQL IN() condition to get all user profiles.
Also, why did you take too many variables for html link. You can do it in single variable using concatenation like following:
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a'
. ' href="';
. 'user_profiles.php';
. '">';
. $row['username'];
. '</a';
. '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
Another mistake is that you are echo ing HTML link and doing redirection.
That will cause headers already sent... error.
This will display list of users with searched string
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$link="<a href='user_profiles.php?user_id=".$row['user_id']."'>".$row['username']."</a>";
}
}
After clicking on link it will redirect to user_profiles.php (no need to header. header is used for automatic redirection)
In user_profiles.php
session_start();
$userID=$_GET['user_id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
Im trying to create a select which is dynamic, for example if there is 3 item in the database gift, then it will create 3 select with value from the database lecturer. This is the javascript to create the select when the user click the button add.
Now after the user have create 3 select and submit it, if the user wish to edit back the data, how can I do it ?
function addField(area,field,limit)
{
var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("select");
var last_item = all_inputs.length - 1;
var last = all_inputs[last_item].id;
if(document.createElement)
{
var li = document.createElement("li");
var input = document.createElement("select");
var opt = document.createElement("option")
input.id = field;
input.name = field;
opt.value = "NULL";
opt.textContent = "NO LECTURER";
li.id = "li"+last_item;
input.appendChild(opt);
li.appendChild(input)
$(document).ready(function()
{
$.ajax
({
type:"post",
url: "event/data.php",
success: function(data)
{
console.log(data);
$(input).append(data);
}
});
});
field_area.appendChild(li);
}
}
Here example of what I have create,
http://i.imgur.com/je1MchL.png
Here how it works
http://i.imgur.com/c4ICTWt.png
So basically in the database have 5 data, so what im trying to do is in the next page it will automatic create the exact 5 select. How can I do this?
Thanks
Create a function (useful for reuse)
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
and call it:
// $options : return array from DB
$curr = 'some_key';
$select_name = 'my_select';
echo create_select($select_name,$options,$curr);
A complete working example:
<?php
// Returns select dropdown
// -----------------------------------------------------------------------
function create_select($name='select', $values = array(), $current='')
{
$select = '
<select name="'.$name.'">';
foreach($values as $key => $value){
$selected = $key == $current ? ' selected = "selected"' : "";
$select .= '
<option value="'.$key.'"'.$selected.'>'.$value.'</option>';
}
$select .= '
</select>
';
return $select;
}
$dbhost = 'localhost:3306';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, $dbname);
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('effone_db');
$query = mysql_query("SELECT * FROM settings");
while ($row = mysql_fetch_array($query)) {
$options[$row['option']] = $row['option_value'];
}
echo create_select('settings',$options,'100');
?>
Let's assume that $options holds the resulting query.
So what you must do is loop thru the items and echo them inside a <select> tag.
like:
<html>
<body>
<select name='nameUrSelectHere'>
<?php
foreach($options as $option){
echo "<option value='" . $option['column_one'] . "'>" . $option['column_two'] . "</option>" ;
}
?>
</select>
</body>
</html>
I've created drop down list with value name from the database. When I select the value from the drop down list, other data will appear in other textfield based on the database. The submit process was doing fine except when I check on the list. The drop down list value didn't appear in the list but other data did.
This is my adding form:
<tr><td width="116">Medicine name</td><td width="221">
<center>:
<select name="name" id="name" >
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
$option_value = $row['priceperunit'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select ></center>
This is a script to display other database value in other textfield when the drop down list is selected:
<script>
var select = document.getElementById('name');
var priceperunit = document.getElementById('priceperunit');
var stock = document.getElementById('stock');
select.onchange = function()
{
var priceperunit_stock = select.value.split(',');
priceperunit.value = priceperunit_stock[0];
stock.value = priceperunit_stock[1];
}
</script>
This is my inserted data into database process:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "arie";
$connect = mysql_connect($host, $user, $pass) or die ('Failed to connect! ');
mysql_select_db($db);
$name=$_POST['name'];
if ($name === "")
{
echo "Please fill all the data";
}
else
{
$query="INSERT INTO `tabelout`(`name`)
VALUES ('$name');";
$result = mysql_query($query) OR die (mysql_error());
echo "You have successfully added new medicine to the database.";
}
?>
This is my list page, where the name didn't show up:
<?php
$con=mysqli_connect("localhost","root","","arie");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tabelout");
echo "<table border='1'>
<th>name</th>";
while($row = mysqli_fetch_array($result))
{
echo "<td><center>" . $row['name'] . "</center></td>";
}
echo "</table>";
mysqli_close($con);
?>
Make sure your database table has records, If it has records, then change the table structure, Add tr tags where required.
echo "<table border='1'>
<tr><th>name</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td><center>" . $row['name'] . "</center></td></tr>";
}
echo "</table>";
I am trying to create a page where it displays a bullet list of Course Title and link to any courses that user is teacher of for Moodle 2.4.
I found this code here and it works for displaying Moodle course categories but not the courses for a user. I am not a programmer so any help would be very appreciated.
<?php
$con = mysql_connect("localhost","moodle","moodle");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
if (isset($result)!=1) {
$message = 'Invalid query: ' . mysql_error() . "\n";
}
echo "<p> The courses taught are: </p>";
///Display Course Categories
$query_catetories = mysql_query('SELECT cc.id, cc.parent, cc.name FROM mdl_course_categories cc ');
$categories = mysql_fetch_all($query_catetories);
$tmp_categories = array();
foreach ($categories AS $row) {
$row['id'] = (int) $row['id'];
$row['parent'] = (int) $row['parent'];
if (!$tmp_categories[$row['parent']])
$tmp_categories[$row['parent']] = array();
$tmp_categories[$row['parent']][] = $row;
}
$course_catetories = buildNode($tmp_categories);
echo '<ul>';
foreach ($course_catetories as $course_catetory) {
print_category_child($course_catetory);
}
echo '</ul>';
function print_category_child($category) {
echo '<li>' . $category['name'];
if (array_key_exists('children', $category)) {
echo '<ul>';
foreach ($category['children'] as $child) {
print_category_child($child);
}
echo '</ul>';
}
echo '</li>';
}
function buildNode($inputArray, $parent = 0) {
$return = array();
foreach ($inputArray[$parent] AS $key => $row) {
if (#$inputArray[$row['id']]) {
$row['children'] = buildNode($inputArray, $row['id']);
}
$return[] = $row;
}
return $return;
}
function mysql_fetch_all($result) {
$all = array();
while ($all[] = mysql_fetch_assoc($result)) {
}
return array_filter($all);
}
///END Course Display
?>'`
Look at your Mysql query :
$result = mysql_query("SELECT name AS COURSE_NAME,parent FROM mdl_course_categories");
Your results are a list of categories' names from the table "mdl_course_categories".
If you want to display a list of courses names, do it using the right table "mdl_course". It may be something like :
mysql_select_db("moodle", $con);
$result = mysql_query("SELECT id, fullname FROM mdl_course WHERE category = "your_course_category_here");
while($row = mysql_fetch_array($result)){
echo $row[0];
echo "<br>";
echo $row[1];
}