I try to keep the value from selected options after the button is clicked.
For now, I have done this with my inputs(range,text) and it's working but I can't figure how to do this with my select option.
ADDITIONAL THINGS(you have to create them to run it)
c13ustawienia.php
<?php
$serwer='localhost';
$uzytk='root';
$haslo='';
$baza='komis';
?>
c13dane.txt
1993|Volkswagen|Passat|19000
1973|Opel|Blitz|12000
1997|Volkswagen|Passat|17000
2010|Mercedes|M5|29000
2001|Volkswagen|Passat|29000
1990|Volkswagen|Passat|23000
2018|Tesla|Super|129000
2018|sla|Super|9000
1992|Volkswagen|Passat|10000
2006|Audi|B9|74000
2009|Volkswagen|Passat|89000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Baza</title>
<style>
table {border-collapse: collapse;}
td,th {border: 1px blue solid;}
th {background-color: azure;}
.id {width: 20px; text-align: center;}
.mar {width: 90px;}
.mod {width: 70px;}
.rok {width: 40px; text-align: right;}
.cena {width: 50px; text-align: right;}
.zolty {background-color: yellow;}
.pomar {background-color:orange;}
[type=text] {width:60px;}
header {height: 60px; background-color:greenyellow;}
header>img {height: 75%; text-align: center;}
nav {height: 400px; width: 30%; background-color:khaki;
float: left;}
main {height: 400px; width: 70%; background-color:moccasin;
float: left;}
footer {height: 40px; background-color: powderblue;
clear: both; text-align: center; color:blue;}
</style>
<script>
function wartosc() {
min=document.getElementById('cmin');
max=document.getElementById('cmax');
wmin=document.getElementById('wmin');
wmax=document.getElementById('wmax');
minint=parseInt(min.value);
maxint=parseInt(max.value);
if(maxint<minint)
maxint=minint+1;
wmin.value=minint;
min.value=minint;
wmax.value=maxint;
max.value=maxint;
}
</script>
</head>
<body>
<?php
function tworz_baze() {
require('c13ustawienia.php');
$link=mysqli_connect($serwer, $uzytk, $haslo);
mysqli_query($link, "DROP DATABASE $baza");
mysqli_query($link, "CREATE DATABASE $baza");
mysqli_query($link, "USE $baza");
mysqli_query($link, "CREATE TABLE auta (
ID int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
marka varchar(20),
model varchar(25),
rok int(4),
cena double)");
return $link;
} // tworz_baze()
function czytajdane($plik) {
$f=fopen($plik, 'r');
while(!feof($f)) {
$linia=rtrim(fgets($f));
if(strlen($linia)>5)
$tab[]=explode('|', $linia);
}
return $tab;
} // czytajdane($plik)
function dobazy($link, $tablica) {
foreach ($tablica as $sam) {
list($rok, $mar, $mod, $cena)=$sam;
mysqli_query($link, "INSERT INTO auta VALUES
(NULL, '$mar', '$mod', $rok, $cena)");
}
} // dobazy($link, $tablica)
function pisz($li, $marka, $cenamin, $cenamax) {
echo "<h3>Wybrano:<br>marka: $marka<br>
zakres cen: $cenamin - $cenamax zł</h3>";
echo "<table>
<tr><th>id</th><th>marka</th><th>model</th>
<th>rok</th><th>cena</th></tr>";
$wyn=mysqli_query($li, "SELECT * FROM auta WHERE
marka='$marka' AND cena>=$cenamin AND cena<=$cenamax");
$licznik=FALSE;
while($wiersz=mysqli_fetch_array($wyn)) {
list($id, $mar, $mod, $rok, $cena)=$wiersz;
$kolor = $licznik ? 'zolty' : 'pomar';
echo "<tr class=\"$kolor\"><th class=\"id\">$id</td>
<td class=\"mar\">$mar</td>
<td class=\"mod\">$mod</td>
<td class=\"rok\">$rok</td>
<td class=\"cena\">$cena</td></tr>";
$licznik=!$licznik;
}
echo '</table>';
mysqli_close($li);
} // pisz($li, $model, $cenamax)
function filtry() {
if(isset($_GET['cmin']))
$tab['cmin']=$_GET['cmin'];
else
$tab['cmin']=0;
if(isset($_GET['cmax']))
$tab['cmax']=$_GET['cmax'];
else
$tab['cmax']=CENAMAKS;
if(isset($_GET['marka']))
$tab['marka']=$_GET['marka'];
else
$tab['marka']='Volkswagen';
return $tab;
} // filtry()
function lista($link) {
$w=mysqli_query($link, "SELECT DISTINCT marka
from auta ORDER BY marka");
while($m=mysqli_fetch_array($w))
echo '<option value="'.$m['marka'].'">'
.$m['marka'].'</option>';
// $x=$m['marka'];
// "<option value=\"$x\">....
} // lista($link)
?>
<header>
<img src="auto.png" alt="auto">
<span>Komis samochodowy</span>
</header>
<nav>
<h3>Filtry:</h3>
<form action="c41.php" method="GET">
Cena:<br>
od: <input type="range" name="cmin" id="cmin"
min="0" max="<?php echo CENAMAKS ?>" value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
do :<input type="range" name="cmax" id="cmax"
min="0" max="<?php echo CENAMAKS ?>"
value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
<input type="text" name="wmin" id="wmin" disabled
value="<?php echo $tf['cenamin'];?>"
> -
<input type="text" name="wmax" id="wmax" disabled
value="<?php echo $tf['cenamax'];?>"
><br>
<select name="marka" id="marka">
<?php lista($li); ?>
</select>
<input type="submit" value="Filtruj">
<input type="reset" value="Czyść">
</form>
</nav>
<main>
<?php pisz($li, $tf['marka'], $tf['cmin'], $tf['cmax']); ?>
</main>
<footer>
Adam Kowal ©
</footer>
</body>
</html>
To make inputs work I have giving them variable of function and pointed right key of database to have what I want, but i have no clue how to make it work with select option
frame of code that gives me what i want in inputs: value="<?php echo $tf['cenamin'];?>"
Change your code with the following:
First add a new parameter to the "lista" function to be able to mark the selected value, e.g.
function lista($link, $selected = "default") {
// function code here
}
Secondly, modify the function to respect the passed value and match it to the value gotten from the database:
while($m=mysqli_fetch_array($w)) {
$status = "";
if ($selected == $m['marka']) $status = "selected";
echo '<option '.$selected.' value="'.$m['marka'].'">' .$m['marka'].'</option>';
}
Thirdly, pass the selected value to the function in your code, e.g.:
<?php lista($li, $_GET['marka']); ?>
NB! You should NOT use your current code in any production environments: it includes several SQL injections and isn't built up by best practises (e.g. separating html from the program code etc).
Related
Hi there i am trying to create a screen in php.
in which i select scenario and the screen displayed accordingly.
but i am stuck in a simple problem that my simple select query is not working
which is
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery) or die("adfasdf");
in same code if change the table name it just work fine, also this table is created in the db as well with the same name i have shared.
here is my complete code.
<?php
include "include/conn.php";
include "include/session.php";
if(isset($_SESSION['logged_user']) && $_SESSION['logged_user'] != '99999'){
header('location: login.php');
}
$query = mysql_query("select curdate() as todayDate");
$show = mysql_fetch_array($query);
if(isset($show)){
$todayDate= $show['todayDate'];
}
$group[] = array();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta Content="no-cache, no-store, must-revalidate" http-Equiv="Cache-Control" />
<meta Content="no-cache" http-Equiv="Pragma" />
<meta Content="0" http-Equiv="Expires" />
<link href="styles/style.css" type="text/css" rel="stylesheet" />
<link href="styles/popupstyle.css" type="text/css" rel="stylesheet" />
<link href="styles/ts.css" type="text/css" rel="stylesheet" />
<link href="styles/calendar.css" type="text/css" rel="stylesheet" />
<style>
table {
font-family: arial;
border-collapse: collapse;
width: 100%;
font-size: 11px;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 3px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
</head>
<body >
</body>
<select id='select_opt'>
<option> Select Assigment </option>
<option value="1"> assign quiz to all Employees </option>
<option value="2"> assign quiz to Sapcific Group </option>
<option value="3"> assign quiz to Sapcific Department </option>
<option value="4"> assign quiz to Sapcific Employee </option>
</select>
<!-- all Users -->
<div id='allUsers' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<select>
<option value=""> select Quiz</option>
</select>
<input type="submit" >
</form>
</div>
<!-- group -->
<div id='group' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>All <input type="checkbox"> </th>
<th>Group Name</th>
<th>Group Code</th>
</tr>
<?php
$group[] = array();
$groupQuery = "Select * from mcb_groups";
$query = mysql_query($groupQuery);
?>
<tr>
<?php if($query){
while($group = mysql_fetch_array($query)){
?>
<td><input type="checkbox" value="<?php echo $group['group_name']; ?>"></td>
<td><?php echo $group['group_name']; ?></td>
<td><?php echo $group['group_code']; ?></td>
</tr>
<?php }
} else{ echo "";} ?>
</table>
</form>
</div>
<!--
####################################
department
####################################
-->
<div id='Department' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action='group_assigment.php' mathod="post">
<table>
<tr>
<th>all <input type="checkbox"> </th>
<th>name</th>
<th>code</th>
<th>group</th>
</tr>
<tr>
<?php
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
?>
<td><input type="checkbox"></td>
<td>code</td>
<td>name</td>
<td>group</td>
</tr>
</table>
<input type="submit" >
</form>
</div>
<!--
####################################
Employee
####################################
-->
<div id='employee' style='margin-left:20px; margin-top: 20px; width: 50%; height:100px; display: none;' >
<form action="" mathod="post">
<label>employee id : </label><input type="text" >
<input type="submit" >
</form>
</div>
<script language="javascript" type="text/javascript">
var elem = document.getElementById("select_opt");
elem.onchange = function(){
console.log("yes i am running");
if( document.getElementById("select_opt").value == "1" ){
document.getElementById("allUsers").style.display = "Block";
document.getElementById("group").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "2" ){
document.getElementById("group").style.display = "Block";
document.getElementById("allUsers").style.display = "none";
document.getElementById("Department").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "3" ){
document.getElementById("Department").style.display = "block";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
document.getElementById("employee").style.display = "none";
}
else if( document.getElementById("select_opt").value == "4" ){
document.getElementById("employee").style.display = "block";
document.getElementById("Department").style.display = "none";
document.getElementById("group").style.display = "none";
document.getElementById("allUsers").style.display = "none";
}
else{
}
};
</script>
</
html>
regard,
Shafee jan
in same code if change the table name it just work fine
Then I would make sure you're connected to the right database. It's surprisingly common for developers to have multiple versions of their database, either on different MySQL instances or else on the same instance under a different schema name. Then they get mixed up, connecting to one database with MySQL Workbench while their app is connecting to a different database.
I would advise that you temporarily add a query to your page to run SHOW TABLES and then dump the result of that query to the log, to confirm that the mcb_department table is present in the database that your PHP script is connected to.
$deptQuery = "Select * from mcb_department";
echo mysql_real_escape_string($deptQuery);
mysql_query($deptQuery);
Where's your error checking? You need to check the return value of mysql_query() every time you run a query, so if there's a problem, you output the error message to your log. Only this way can you start to solve some of these problems.
$result = mysql_query($deptQuery);
if (!$result) {
trigger_error("Error in file " . __FILE__ . " near line " . __LINE__
. " for query $deptQuery: " . mysql_error());
die("Database error");
}
PS: The advice of some commenters that mysql_* functions are deprecated is true, but probably irrelevant to your question. Folks who focus on the API, when you have said the API is working, are just being pedantic.
I can't seem to get $_POST to work with my sql query. I have tried both mysql_query and PDO.
$newartist = $_POST['newartist']; // This doesn't work with PDO statement
//$newartist = 'Hubert De Lartigue'; // This works with PDO statement!
//$query = $DBH->prepare("SELECT * FROM artist WHERE artist =?"); // Original Method
//$query->bindValue(1, $newartist, PDO::PARAM_STR); // Original Method
$query = $DBH->prepare("SELECT * FROM artist WHERE artist = :newartist"); // Suggested Method
//$query->bindParam(':newartist', $newartist); // Suggested method, tested
$query->bindParam(':newartist', $newartist, PDO::PARAM_STR); // Suggested method
$query->execute();
//foreach ($query as $row) { // Switched to while loop so it can "fetch"
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$selectedartist = '<option value="'.$row['artist_id'].'" selected="selected">'.$row['artist'].'</option>';
}
I can however echo $_POST['newartist']; and it will correctly output the artist's name!
The form per request (NOTE: you have to click the + to submit an artist and newartist echos properly after submitting a new artist):
<div style="background: #270126; padding: 0 20px;" id="artist" >
<form method="post" style="width: 100%">
Artist: <select name="artist" style="width: 200px; background: black;" class="required">
<?php
if(!empty($_POST['newartist'])) {
echo $selectedartist;
} else {
echo '<option value="2" selected="selected">Unknown-Artist</option>
'.$theartist.'';
}
?></select> +</div>
<div style="background: #270126; padding: 0 20px;" id="addnewartist" >
<fieldset style="display: none;height: 35px;" id="artistnew">
Artist Name:
<input name="newartist" id="newartist" style="width: 200px; display:inline;" /> Artist URL:<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" style="display:inline;" />
</fieldset>
</div>
<fieldset id="artworknew" style="width: 100%;">
<div style="background: #270126; padding: 0 20px;">
Artwork Name: <input name="name" id="name" style="width: 300px;" />
</div>
<div style="background: #270126; padding: 0 20px;">
File Name: <input name="file" id="file" style="width: 300px" value=".jpg" /><br />
</div>
<div style="background: #270126; padding: 0 20px; height: 35px;">
Folder: <select name="folder" style="width: 200px; background: black;">
<option value="16">digitalart2</option>
<?=$thefolder;?></select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div></fieldset>
</form>
</div>
<?php
if ($_POST['addartist']) {
mysql_query("INSERT INTO `artist` ( `artist_id` , `artist`, `artist_url`)
VALUES (NULL , '".$_POST['newartist']. "', '".$_POST['artist_url']. "');") or die(mysql_error());
//echo '<meta http-equiv="refresh" content="0;url=?form=addart">';
}
if ($_POST['addartwork']) {
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
mysql_query("INSERT INTO `artwork` (`id`, `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($_POST['name'])."',
'".sql_inj_str($_POST['artist'])."',
'".sql_inj_str(htmlentities($_POST['file']))."',
'".sql_inj_str($_POST['folder'])."',
'".sql_inj_str($_POST['dt1'])."',
'1',
'".sql_inj_str($_POST['disabled'])."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}
include ('footer.php');
?>
I went through all the code you gave me. You have many bad html, css and javascript practices. It make your code hard to debug. I have improved your code and maybe if you can follow my logic and comments, you will figure out what's wrong with you code.
Basically, the code you showed me first is perfectly fine. The problem is with your design. You are entering null values for the id column instead of letting the database do it for you. You have a column for an artist_id and inserting in the artist there. Look at your database definitions to make sure that they have the correct structure and are getting the expected variables. Here is you code but made with good practices. If you can follow my code, you will find it easier to debug the problem.
<?php
/** I have re-wrote your code to give you a better way of writing code that makes it easier to debug**/
/**Store input fields as variables so I don't have to repeat certain things**/
$newartist = isset($_POST['newartist']) ? ($_POST['newartist']) : "Unkown Artist"; // either has a value or the value is Unknown Artist. Only has a value if the $_POST is set
$addartist = isset($_POST['addartist']) ? true : false; // the addartist has been posted or not
$addartwork = isset($_POST['addartwork']) ? true : false; // the addartwork has been posted or not
//This is for add new artist
if($addartist){
$newartist = isset($_POST['newartist']) ? $_POST['newartist'] :null;
$newartist = isset($_POST['artist_url']) ? $_POST['artist_url'] :null;
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
mysql_query("INSERT INTO `artist` ( `artist`, `artist_url`)
VALUES ('". $newartist . "', '". $artist_url . "');") or die(mysql_error());
}else{
$newartist = null;
$artist_url = null;
}
/// this is for adding artwork
if($addartwork){
$name = isset($_POST['name']) ? $_POST['name'] :null;
$artist = isset($_POST['artist']) ? $_POST['artist'] :null;
$file = isset($_POST['file']) ? htmlentities($_POST['file']) :null;
$folder = isset($_POST['folder']) ? $_POST['folder'] :null;
$dt1 = isset($_POST['dt1']) ? $_POST['dt1'] :null;
$disabled = isset($_POST['disabled']) ? 1 : 0;
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
//There is a problem with you artist_id column. The artist has a string value, and you have an id column in the database
//Also you have a sql_inj_str() function. I am guessing that you have difined this function somewhere.
mysql_query("INSERT INTO `artwork` ( `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($name)."',
'".sql_inj_str($artist)."',
'".sql_inj_str(htmlentities($file))."',
'".sql_inj_str($folder)."',
'".sql_inj_str($dt1)."',
'1',
'".sql_inj_str($disabled)."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}else{
$name = null;
$artist = null;
$file = null;
$folder = null;
$dt1 = null;
$disabled = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Query PDO</title>
<!-- Put the styles (CSS) seperate from the html, easier to maintain. You can just copy these styles into an external file and just link it-->
<style>
#artist {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
form {
width: 100%;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
select {
width: 200px;
/**background: black;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
a {
width: 15px;
font-size: 1.5em;
display:inline;
/**added a myself**/
text-decoration: none;
}
#addnewartist{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
fieldset#artistnew{
display: none;
height: 35px;
}
form #newartist {
width: 200px;
display:inline;
}
form .secondaryAction{
display:inline;
}
#artworknew{
width: 100%;
}
/** I now had no choice but to add in a few class names here**/
.ArtworkName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='name'] {
width: 300px;
}
.FileName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='file'] {
width: 300px;
}
.Folder {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
height: 35px;
}
select[name='folder'] {
width: 200px;
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
</style>
</head>
<body>
<form method="post">
<!-- move the div inside the form-->
<div id="artist" >
Artist:
<select name="artist" class="required">
<?php echo '<option value="' . $newartist . '" selected="selected">' . $newartist . '</option>'; ?>
</select>
<!--When the link is clicked it runs the doStyles function-->
+
<!-- get all the javascript out of the anchor tag. You can use jquery or external javscript but doing it this way is really really bad practice-->
<script>
// You can store this code in an external javscript file and embed it here
function doStyles(){
document.getElementById('artistnew').style.display='block';
document.getElementById('artworknew').style.display='none';
document.getElementById('artist').style.display='none';
}
</script>
</div>
<div id="addnewartist" >
<fieldset id="artistnew">
Artist Name:
<input name="newartist" id="newartist" />
Artist URL:
<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" />
</fieldset>
</div>
<fieldset id="artworknew" >
<div class="ArtworkName">
Artwork Name:
<input name="name" id="name" />
</div>
<div class="FileName">
File Name:
<input name="file" id="file" value=".jpg" /><br />
</div>
<div class="Folder">
Folder:
<select name="folder" >
<option value="16">digitalart2</option>
<?=$thefolder;?>
</select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
Everything looks OK. Check you form again, and make sure the name attribute is correct. Also, if you are typing in the name on the search form, make sure you are taking care of the case sensitive. The name should match the name in the database.
Use bindParam
Try taking out the PDO::PARAM_STR for now.
Lastly try this:
$result = $query->execute();
and then use $result in the for each loop
I am having two drop down lists on a html page. The data is coming from a mysql database and contains information like latitude, longitude and address. The user selects one item from the drop down and clicks on submit.
At this stage, I want to display a google map and put a marker at the latitude and longitude. Then, when the user selects the option from second drop down, I want to just add a marker on that map.
Currently, I am able to load the map once he clicks the submit from first drop down but all the options I tried to drop the pins are not working.
Here is the code I have achieved till now:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once('auth.php');
include ('LoginConfig.php');
include ('FetchAgentDetails.php');
include ('FetchDeliveryDetails.php');
?>
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Delivery Management System</title>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA0Rm5aK0BYu1f_TzhjkG97cchHHlQfrQY&sensor=false">
</script>
<style type="text/css">
html {height:100%}
body {height:100%;margin:0;padding:0}
#googleMap {height:100%}
</style>
<script>
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<style type="text/css">
<!--
.style1 {
font-size: 20px;
font-weight: bold;
}
-->
</style>
<style type="text/css">
table.collection {width:250px;border:2px solid black;border-style: outset;border-collapse:collapse;}
table.collection tr {background-color:#fff; border-bottom: 1px #99b solid;padding:10px;}
table.collection tr:hover {background-color:#ffe;}
table.collection td {display:table-cell;border-bottom: 1px #99b solid; padding:10px;}
table.collection td a {text-decoration:none; display:table-row; padding:0px; height:100%;}
</style>
</head>
<body bgcolor="#8E8E38"
<div style="clear: right;">
<p align="left" class="style1">Welcome Delivery Manager! </p>
<img style="position: absolute; top: 0; right: 0;" src="./Images/logo.jpg" alt="Company Logo" width="90" height="60" align="middle"></img>
</div>
<p align="left">Home</p>
<hr></hr>
<!-- START Main Wrap -->
<form method="post">
<fieldset>
<div style="clear: left;float:left;">
<label for="deliveryList">Delivery Items:</label>
<select name="deliveryList" id="deliveryList">
<option value="Select delivery item" selected="selected">Select delivery item</option>
<?php
$deliveryHandler = new FetchDeliveryDetails();
$itemNameArray = $deliveryHandler->getItemNames();
foreach ($itemNameArray as $innerArray) {
if (is_array($innerArray)) {
$value = $innerArray['itemName'];
echo "<option value=\"$value\"";
if (isset($_POST['deliveryList']) && $_POST['deliveryList'] == $value)
echo 'selected';
echo ">" . $value . "</option>\n";
}
}
?>
</select>
<input type="submit" name="submit" id="submit" value="Submit"/>
</div>
<div style="clear: right;float:right;">
<label for="agentList">Avaliable Agent:</label>
<select name="agentList" id="agentList">
<option value="" selected="selected">Select agent to assign</option>
<?php
$agentHandler = new FetchAgentDetails();
$agentNameArray = $agentHandler->getAgentNames();
foreach ($agentNameArray as $innerArray) {
if (is_array($innerArray)) {
$agentId = $innerArray['agentId'];
$firstNameValue = $innerArray['firstname'];
$lastNameValue = $innerArray['lastname'];
$fullName = $firstNameValue . ' ' . $lastNameValue;
echo "<option value=\"$agentId\">$fullName</option>\n";
}
}
?>
</select>
<input type="submit" name="agentSubmit" id="agentSubmit" value="Check Location"/>
</div>
</fieldset>
</form>
<?php
if (isset($_POST['deliveryList'])) {
$selectedItemName = $_POST['deliveryList'];
$deliveryHander = new FetchDeliveryDetails();
$itemDetailsArray = $deliveryHander->getAllDeliveryDetails($selectedItemName);
foreach ($itemDetailsArray as $valuesArray) {
$itemNameValue = $valuesArray['itemName'];
$itemDescriptionValue = $valuesArray['itemDescription'];
$ownerFirstname = $valuesArray['firstName'];
$ownerLastname = $valuesArray['lastName'];
$dateAdded = $valuesArray['dateAdded'];
$deliveryDate = $valuesArray['deliveryDate'];
$deliveryAddress = $valuesArray['deliveryAddress'];
$deliveryLatitude = $valuesArray['deliveryLatitude'];
$deliveryLongitude = $valuesArray['deliveryLongitude'];
$assignedAgent = $valuesArray['assignedAgentId'];
if ($assignedAgent == 0) {
$assignedAgent = "-";
}
echo "<table border=\"1\" align=\"left\" class =\"collection\">\n";
echo "<tr>\n";
echo "<td >Item Name:<b>$itemNameValue</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Item Description: <b>$itemDescriptionValue</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Owner Name: <b>$ownerFirstname $ownerLastname</td>\n";
echo "</tr>\n";
echo "<tr>\n";
echo "<td>Date Added: <b>$dateAdded</td>\n";
echo "</tr>\n";
echo "<tr>";
echo "<td>Delivery Date: <b>$deliveryDate</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Delivery Address: <b>$deliveryAddress</td>";
echo "</tr>";
echo "<tr>";
echo "<td>Assigned Agent: <b>$assignedAgent</td>";
echo "</tr>";
echo "</table>";
echo "<div id=\"googleMap\" style=\"width:500px;height:380px;\"></div>";
}
}
if (isset($_POST['agentList'])) {
}
?>
</body>
</html>
I almost forgot, this is my first PHP application, in fact my first web application. So please go easy on me. Point out other errors also, but please stick to the question.
Ok got it working by using iframe :) and a bit of php
Reference:
http://www.youtube.com/watch?v=HTm-3Cduafw
echo "<iframe style =\"display: block;
width: 800px;
padding-top: 2px;
height: 400px;
margin: 0 auto;
border: 0;\" width=\"425\" height=\"350\" align=\"center\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\"
src=\"https://maps.google.com/maps?f=d&source=s_d&saddr=$agent_map_url&
daddr=$map_url&hl=en&z=10&t=m&mra=ls&ie=UTF8&output=embed\"></iframe><br/>";
I have an editable grid where I want to edit the CSS such that the textarea to show the maximum width, but somehow I can't increase the width of the text area.
My database has three columns:
ID
Name
Gossip
I'm retrieving everything and displaying it in an editable grid using PHP.
index.php code
<?php
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
die('Check the database connection again!');
}
$userQuery = 'SELECT Id,Name,Gossip FROM bollywood';
$stmt = $db->query($userQuery);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var textBefore = '';
$('#grid').find('td input').hover(function() {
textBefore = $(this).val();
$(this).focus();
}, function() {
var $field = $(this),
text = $field.val();
$(this).blur();
// Set back previous value if empty
if (text.length <= 0) {
$field.html(textBefore);
} else if (textBefore !== text) {
// Text has been changed make query
var value = {
'row': parseInt(getRowData($field)),
'column': parseInt($field.closest('tr').children().find(':input').index(this)),
'text': text
};
$.post('user.php', value)
.error(function() {
$('#message')
.html('Make sure you inserted correct data')
.fadeOut(3000)
.html(' ');
$field.val(textBefore);
})
.success(function() {
$field.val(text);
});
} else {
$field.val(text);
}
});
// Get the id number from row
function getRowData($td) {
return $td.closest('tr').prop('class').match(/\d+/)[0];
}
});
</script>
<title></title>
</head>
<body>
<?php if ($stmt): ?>
<div id="grid">
<p id="message">Click on the field to Edit Data</p>
<table>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Gossip</th>
</tr>
</thead>
<tbody>
<?php while ($row = $stmt->fetch_assoc()): ?>
<tr class="<?php echo $row['Id']; ?>">
<td><input type="text" value="<?php echo $row['Id']; ?>" /> </td>
<td><input type="text" value="<?php echo $row['Name']; ?>" /></td>
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<?php else: ?>
<p>No actors added yet</p>
<?php endif; ?>
</body>
</html>
user.php code
<?php
// Detect if there was XHR request
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$fields = array('row', 'column', 'text');
$sqlFields = array('Id', 'Name', 'Gossip');
foreach ($fields as $field) {
if (!isset($_POST[$field]) || strlen($_POST[$field]) <= 0) {
sendError('No correct data');
exit();
}
}
$db = new mysqli('localhost', 'root', '', 'bollywood');
$db->set_charset('utf8');
if ($db->connect_errno) {
sendError('Connect error');
exit();
}
$userQuery = sprintf("UPDATE bollywood SET %s='%s' WHERE Id=%d",
$sqlFields[intval($_POST['column'])],
$db->real_escape_string($_POST['text']),
$db->real_escape_string(intval($_POST['row'])));
$stmt = $db->query($userQuery);
if (!$stmt) {
sendError('Update failed');
exit();
}
}
header('Location: index.php');
function sendError($message) {
header($_SERVER['SERVER_PROTOCOL'] .' 320 '. $message);
}
style.css code
body {
font: normal 14px Comic Sans, Comic Sans MS, cursive;
}
table {
width: 500px;
}
td, th {
border: 1px solid #d8d8bf;
}
th {
padding: 5px;
font: bold 14px Verdana, Arial, sans-serif;
}
td {
padding: 10px;
width: 200px;
}
td input {
margin: 0;
padding: 0;
// width:200px;
font: normal 14px sans-serif;
/** Less flicker when :focus adds the underline **/
border: 1px solid #fff;
}
td input:focus {
outline: 0;
border-bottom: 1px dashed #ddd !important;
}
#grid input {
// width: 200%;
}
You doing it wrong
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
Should be:
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
textarea is html tag name but not input type. so change this.
<td ><input type="textarea" cols="500" rows="100" value="<?php echo $row['Gossip']; ?>" /></td>
to
<td ><textarea cols="500" rows="100"><?php echo $row['Gossip']; ?></textarea>
also add this css.
<style>
textarea {
resize: both;
width:700px;
}
</style>
also are you sure that you can get content using this.
<?php echo $row['Gossip']; ?>
I wonder whether someone may be able to help me please.
From some demos and tutorials I've found, I've put together this page which adds toggle panes to a page using values from a mySQL database to populate the fields.
The problem I'm having is that at each layer only the first out of multiple records is shown.
e.g. The screen currently shows 16/03/2012 as the only record, there should be one other record for the 23/02/2012.
Then within the 16/03/2012, the next level should show two items, whereas it is only showing one.
I've been working on this for a while now but I can't seem to find the solution of how to show the correct number of records.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
I've added the full script below for reference.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Panel Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});
</script>
<style type="text/css">
body {
margin: 20px auto;
font: 12px Verdana,Arial, Helvetica, sans-serif;
}
.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }
</style>
</head>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
{
}
}
}
?>
<body>
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
</body>
</html>
Many thanks and kind regards
You are fetching all the records but using only the last one.
You should put this:
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
in the while loop which fetch the data:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
So it will look like this:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
echo '<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="'.$dateoftrip.'" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="'.$findname.'" disabled="disabled"/>
</div>
</div>';
}
You need to put your output inside your loop. Also you may have to modify your javascript to account for the multiple content ids.
You should also make the form controls into arrays so you'll be able to parse them if needed (see below).
For example, this is how to modify the form.
?>
<body>
<div class="layer1">
<?php
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
$i++;
?>
<p class="heading"><input name="dateoftrip[]" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname[]" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
<?php
{
}
}
}
?>
</div>
</div>