I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
Related
<html><head></head><body>
<?php
$db_hostname = "mysql";
$db_database = "u1da";
$db_username = "u1da";
$db_password = "1234";
$con = mysql_connect($db_hostname ,$db_username ,$db_password);
if (!$con) die ("Unable to connect to MySQL: ".mysql_error ());
mysql_select_db ( $db_database ) ||
die (" Unable to select database : ". mysql_error());
$query = "select * from students";
$result = mysql_query($query);
$result || die ("Database access failed: ".mysql_error());
$rows = mysql_num_rows($result);
echo "<table border=1>";
echo "<tr><td><p><b>Name</b></p></td></tr>";
for ($j = 0; $j < $rows ; $j ++) {
echo "<tr><td>", mysql_result($result,$j,'name') ,"</td></tr>";
}
echo "</table><br />";
$query2 = "select * from groups";
$result2 = mysql_query($query2);
$result2 || die ("Database access failed: ".mysql_error());
$rows2 = mysql_num_rows($result2);
echo "<table border=1>";
echo "<tr><td><p><b>Tutorial Group</b></p></td><td><p><b>Capacity</b></p></td></tr>";
for ($i = 0; $i < $rows2 ; $i ++) {
echo "<tr><td>", mysql_result($result2,$i,'Tutorial_Group') ,"</td><td>", mysql_result($result2,$i,'Capacity') ,"</td></tr>";
}
echo "</table>";
echo "<form method='post' action='' enctype="multipart/form-data">";
$query3 = "select * from students";
$result3 = mysql_query($query3);
echo "<br /><br /><select name='name'>";
while($name = mysql_fetch_array($result3)) {
echo "<option value='$name[Name]' > $name[Name] </option>"."<BR>";
}
echo "</select><br />";
$query4 = "select Tutorial_Group from groups";
$result4 = mysql_query($query4);
echo "<select name = 'group'>";
while($grp = mysql_fetch_array($result4)){
echo "<option value='$grp[Tutorial_Group]'>$grp[Tutorial_Group]</option>";
}
echo "</select><br />";
echo "Student ID: ";
echo '<input type="text" name="SID"><br />';
echo "Email: ";
echo '<input type="text" name="email"><br />';
echo '<input type="submit" name="submit" value="Submit">';
echo "</form>";
?>
Here is my current script code.
I have to make a query which will get the value from the 2 drop-down menus and 2 text fields and insert them into a table.
Table is called assg and have columns: Name, Student_ID, email, s_group. I have tried some different ways, but it didn't worked out. Please help.
Your first problem is that you are using mysql_fetch_array to get an array of elements into $grp variable but next you try to use it with a associative array to get values like $grp[Tutorial_Group]
Using mysql_fetch_array you can get $grp[0] ... $grp[1] but not $grp[Tutorial_Group]
You need to use mysql_fetch_assoc to get associative arrays like $grp[Tutorial_Group]
Your second problem is using complex php vars incorrectly example
Incorrect:
echo "<option value='$grp[Tutorial_Group]'>$grp[Tutorial_Group]</option>";
Correct:
echo '<option value="'.$grp['Tutorial_Group'].'">'.$grp['Tutorial_Group'].'</option>';
Or
echo "<option value='{$grp['Tutorial_Group']}'>{$grp['Tutorial_Group']}</option>";
Also the code only has the part to view the tables and the form. The insert part of the data is missing in the example. Probably this part has also some errors.
No indentation, html in echos, i don't even understand what you want.
By dropdown you mean select ?
What about $_POST['nameOfTheField'] ?
And why multipart ? There's no files to send here.
I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function
I have a simple program that I am trying to implement some sort of pagination/capability to navigate through individual records in a MySQL database. The code itself calls a function that returns an associative array so that the records may be navigated sequentially in the case of non-sequential indices being made by deletes.
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray; }
I am attempting to store the result from this function into a variable and from there try to increment that variable for use in an other function:
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
I would then use the $row to display the current workstation :
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method ='post'>";
echo "<b>Workstation Name:</b><br><input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . " </option>";
echo "</select></br>";
I was wondering if I was going about this completely wrong or how I would approach incrementing the array's index to display each record on a click of an anchor tag or button the whole file is as follows :
<html>
<body>
<div>
<?php
$un = "xxx";
$pw = "xxxxxx";
$dsn = "mysql:host=127.0.0.1;dbname=xxxxxxxxxxx";
$Keys = getKeys($dsn,$un,$pw);
$i = 0;
$currID = $Keys[$i][0];
$row = getResultSet($dsn,$un,$pw,$currID);
echo "<hr class='viewHR'>";
echo "</br></br><div class='viewFormat'>";
echo "<form name = 'updateWorkstationForm' action ='updateWorkstation.php' method = 'post'>";
echo "<b>Workstation Name:</b><br> <input type = 'Textbox' name = 'pcName' value = '" . $row['Workstation_Name'] . "'/></br>";
echo "<b>Serial Number: </b><br> <input type = 'Textbox' name = 'SN' value = '" . $row['Serial_Number'] . "'/></br>";
echo "<b>Model</b></br>";
echo "<select name ='modelSelect'>";
echo "<option value = '".$row['Model_ID'] . "'>" . $row['Model'] . "</option>";
echo "</select></br>";
echo "<b>Department</b></br>";
echo "<select name ='DepartmentSelect'>";
echo "<option value = '".$row['Department_ID'] . "'>" . $row['Department'] . "</option>";
echo "</select></br>";
echo "<b>Room</b></br>";
echo "<select name ='RoomSelect'>";
echo "<option value = '".$row['Room_ID'] . "'>" . $row['Room'] . "</option>";
echo "</select></br>";
echo "<b>Property Status</b> </br>";
echo "<select name = 'propertyStatus'>";
echo "<option value = '".$row['Property_Status_ID'] . "'>" . $row['Property_Status'] . "</option>";
echo "</select></br>";
if ($row['Property_Status'] != "Owned"){
echo "<b>Lease Company:</b> ";
echo "<select name = leaseSelect>";
echo "<option value = '" . $row['Lease_Info_ID'] ."'>Company:" . $row['Company'] . ", Start: " . $row['Start_Date'] . "End: " .$row['End_Date'] . "</option>";
echo "</select></br>";
}
echo "<b>Cart</b></br>";
echo "<select name ='cartSelect'>";
echo "<option value = '".$row['Cart_ID'] . "'>" . $row['Cart_Type'] . "</option>";
echo "</select></br>";
echo "<b>Workstation Comments: </b><br> <Textarea rows='5' cols='60' name = 'wsComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<b>Location Comments: </b><br> <Textarea rows='5' cols='60' name = 'locComments'> ". $row['Workstation_Comment'] . " </Textarea></br>";
echo "<input type = 'submit' value = 'Update' />";
echo "<input type = 'button' value = 'Cancel' onclick = 'location.reload(this);' />";
echo "</form>";
echo "</div>";
/*Function to return a parallel array. This is so that non-sequential records in the database may be described sequentially with the help of an array's indices*/
function getKeys($handle, $user, $password) {
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation_ID from Workstation";
$result = $conn -> query($sql);
$resultArray = array();
while ( $row = $result -> fetch()) {
$resultArray[] = $row;
}
$conn = null;
return $resultArray;
}
function getResultSet($handle, $user, $password, $ID) {
$resultSet = "";
try {
$conn = new PDO($handle,$user,$password);
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Error connectiong to database. Error: (" . $e -> getMessage() . ")";
}
$sql = "Select Workstation.Workstation_ID,Workstation.Model_ID,Workstation.Property_Status_ID,workstation.Lease_Info_ID, Workstation.Workstation_Name, Workstation.Serial_Number, Model.Model, Department.Department,Room.Room,Property_Status.Property_Status,Lease_Info.Start_Date,Lease_Info.End_Date,Lease_Info.Company,Lease_Info.Lease_Comment,Cart.Cart_Type,Workstation.Workstation_Comment,Workstation.Location_Comment from Workstation INNER JOIN Model ON Workstation.Model_ID = Model.Model_ID INNER JOIN Department ON Workstation.Department_ID = Department.Department_ID INNER JOIN Room ON Workstation.Room_ID = Room.Room_ID INNER JOIN Property_Status ON Workstation.Property_Status_ID = Property_Status.Property_Status_ID INNER JOIN Lease_Info ON Workstation.Lease_Info_ID = Lease_Info.Lease_Info_ID INNER JOIN Cart ON Workstation.Cart_ID = Cart.Cart_ID where Workstation_ID = :ID";
$pstmt = $conn -> prepare($sql);
if(!$pstmt) {
echo "Error preparing the statement. Error: (" . $conn -> ErrorInfo() . ")";
}
$pstmt -> bindParam(':ID', $ID);
try {
$pstmt -> execute();
}
catch(PDOException $e) {
echo "Failed to execute prepared Statement. Error: (" . $e -> getmessage() . ")";
}
$resultSet = $pstmt -> fetch();
return $resultSet;
$conn = null;
}
?>
</div>
</body>
</html>
Any criticism, insight, or pointers would be greatly appreciated.
You shouldn’t be fetching all records if you only intend to display a subset, or just one.
To paginate, use the LIMIT clause. So, if you split records into pages of ten, then to get the first page your query would be:
SELECT * FROM workstations LIMIT 0,10
Where the first number is the offset, and the second number is the number of records after the offset you wish to fetch. To fetch the second page, you’d change the limit clause to be LIMIT 10,10; to fetch the third page LIMIT 20,10, and so on. The PHP equation is:
$offset = (($page - 1) * $records_per_page);
The page value can come from a $_GET variable, like http://www.example.com/?page=1.
Secondly, if you’re only wanting to display one record, then fetch that one:
SELECT * FROM workstations WHERE id = ? LIMIT 1
Pass the ID via a $_GET parameter again, and use PDO to bind it to avoid SQL injection vulnerabilities:
<?php
$sql = "SELECT * FROM workstations WHERE id = :id LIMIT 1";
$sth = $db->prepare($sql);
$sth->bindParam(':id', $_GET['id'], PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetchObject();
I am populating a drop down menu from mysql database. It works well, But I want it not to repeat values. (i.e if some value is N times in database it comes only once in the drop down list)
Here is my code:
<?php
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['year'] . "'>" . $row['year'] . "</option>";
}
echo "</select>";
?>
Use DISTINCT in your query.
"SELECT DISTINCT year FROM data";
just change Your query. is better
$sql = "SELECT distinct year FROM data";
Another technique:
select year from table group by year
in PHP side you have to do this
$all_data = array();
echo "<select name='year'>";
while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
array_push($all_data,$row["column"]);
}
$all_data = array_unique($all_data);
foreach($all_data as $columns => $values){
print("<option value='$value'>$value</option>");
}
echo "</select>";
Here is a simple trick. Take a boolean array. Which value has not come in list print it in list and which value has come in list already once, set it as true through indexing the boolean array.
Set a condition, if boolean_array[ value ] is not true, then show value in list. Otherwise, don't.
mysql_connect('host', 'user', 'pass');
mysql_select_db ("database");
$sql = "SELECT year FROM data";
$result = mysql_query($sql);
echo "<select name='year'>";
while ($row = mysql_fetch_array($result)) {
if($bul[$row['year']] != true){
echo "<option value='" . $row['year'] . "'>" . $row['year'] . " </option>";
$bul[$row['year']] = true;
}
}
echo "</select>";
?>
What i'm trying to do is display a drop down with all field names from mysql database, once the user picks one and submits the form i want to display a second dropdown filled with all the rows from the submitted field name, this is my code so far:
$result = mysql_query("select * from `parts`") or die(mysql_error());
echo "<form action='".$_SERVER['PHP_SELF']."' method='post'>";
echo "<select name='field_names'>";
$i = 0;
while ($i < mysql_num_fields($result)) {
$fieldname = mysql_field_name($result, $i);
echo '<option value="'.$fieldname.'">'.$fieldname.'</option>';
$i++;
}
echo "</select>";
echo "<input type='submit' value='submit'></input>";
echo "</form>";
if($_POST) {
$fields = $_POST['field_names'];
$result1 = mysql_query("select '".$fields."' from `parts`") or die(mysql_error());
echo '<select name="fields">';
while ($row = mysql_fetch_array($result1)) {
echo "<option value=".$row[$fields].">".$row[$fields]."</option>";
}
echo '</select>';
}
Can anyone spot where i'm going wrong, thanks
there is a mistake on the line number 29
$result1 = mysql_query("select '" . $fields . "' from `parts`") or die(mysql_error());
you are using ' instead of `. Do as follows
$result1 = mysql_query("select `" . $fields . "` from `parts`") or die(mysql_error());
Hope your problem is solved.
As it stands now, the second set of selects will be issued OUTSIDE of your </form> tag, so will never get submitted with the rest of the form. At best, you should move the form closing tag to below the POST handler.
here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}
echo "</select>";
here username is the column of my table(userregistration)
it works perfectly