Send ID instead Name in PHP and MYSQL - php

Problem:
i want to send ID to database table instead of Name. but i want to display Name in a field instead of ID.
it work's well while i send it through combo box. but i don,t know how it work with Search field. the php code is given below:
<font> <b>Name: </b></font>
<?php
include("database/db.php");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM table";
$result = $link->query($sql); ?>
<select name="ID">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$ad_id = $row["ID"];
$name= $row['Name'];
?>
<option value="<?php echo $ad_id; ?>"><?php echo $name; ?></option>
<?php
}
} else {
echo "0 results";
}
// close connection
mysqli_close($link);
?>
</select>

As per your comment you can use the auto complete text box in php from mysql by using ajax call it will fulfill your requirement for search by name.
There are some link available in web as you can search and implement but you have to do some changes for the ID contact with NAME
Autosuggest ref 1
Autosuggest link ref 2
JQUERY UI

Related

How do I store value in my database in a dynamic dropdown list?

This is a dynamic dropdown in PHP/mySQL.
I want to store the name in the database server but the tag outputs the integer value.
If i change the code from <option value="<?php echo $row["id"]; ?>"> to <option value="<?php echo $row["name"]; ?>"> It shows my_sqli_fetch_array expects parameter 1 error.
My objective being to store the corresponding $row["name"] that is being displayed on the dropdown instead of $row["id"].
<?php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
?>
<form name="form1" action="" method="post">
<table>
<tr>
<td>Select Assembly Line</td>
<td><select id ="assemblylinedd" onChange="change_assemblyline()">
<option>Select</option>
<?php
$i=1;
$res=mysqli_query($link, "SELECT * FROM assemblyline");
$count=mysqli_num_rows($res);
if ($count >0){
while($row=mysqli_fetch_array($res))
{
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
}
<?php $i++;} }else{
echo "No record Found !";
} ?>
</select></td>
</tr>
Scripting code :
<script type="text/javascript">
function change_assemblyline()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?assemblyline="+document.getElementById("assemblylinedd").value, false);
xmlhttp.send(null);
alert(xmlhttp.responseText);
document.getElementById("devices").innerHTML=xmlhttp.responseText;
}
This is my ajax.php
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link,"loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if($assemblyline!="")
{
$res=mysqli_query($link, "SELECT * FROM devices WHERE devices_id=$assemblyline");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row=mysqli_fetch_array($res))
{
echo "<option value='$row[id]'>";echo $row["name"]; echo "</option>";
}
echo "</select>";
}
Please do ignore onchange_devices() as it follows the same for next consecutive dropdown.
Though, its your requirement to save device name in DB, it is advised to save numeric id.
Reason: Name may change, but, id will persist.
If say your device id:name is 99 : iPhone 6 and you save in DB: iPhone 6, later the name gets changed to iPhone6.
In this scenario if you search records with name iPhone6, clearly, your above record will not show.
If you save numeric id, it will show irrespective of name change.
Coming back to your question:
I cannot write code here. But a pseudo code logic will help (hope so):
Take a hidden field device_name.
On change of drop down, with jQuery, assign value to hidden field.
$("#assemblylinedd option:selected").text();
Now, after submit, you will get device_name in hidden field.
$devices = isset($_GET['device_name']) ? $_GET['device_name'] : '';
Save this to DB.
$link = mysqli_connect("localhost","root", "");
mysqli_select_db($link, "loginsystem");
$assemblyline = isset($_GET['assemblyline']) ? $_GET['assemblyline'] : '';
$devices = isset($_GET['devices']) ? $_GET['devices'] : '';
if(!empty(trim($assemblyline)))
{
$res = mysqli_query($link, "SELECT * FROM devices WHERE devices_id = '$assemblyline'");
echo "<select id='devicesdd' onchange='change_devices()'>";
while($row = mysqli_fetch_array($res))
{
echo "<option value='" . $row["id"] . "'>" . $row["name"] . "</option>";
}
echo "</select>";
}
I've added a proper empty check instead of your != "", which didn't previously prevent a single space from being passed.
I've quoted your query value, I would definitely use prepared statements instead of passing values directly.
I've quoted your $row[id].
I've concatenated your string correctly.
Note: It would be preferable to return a JSON array object with the IDs and the names instead of outputting HTML via the AJAX, it would make your code-base much cleaner and adaptable in the future.
Reading Material
empty
trim

Populating HTML Dropdown List using PHP/MYSQL

I was practicing using HTML/PHP/MySQL, and was working on a small project.
I wanted to create a page that would allow the user to add records to a MySQL table. The user would enter the values via an HTML form. This data would then be posted to a php script to perform the actual INSERT INTO.
The database is for a shop, and has 2 tables, product and manufacturer. When adding a product, I must also add a code for the manufacturer. I want to populate a dropdown list, showing the names of manufacturers (taken from the manufacturers table).
I am attempting to embed this PHP code into an HTML file. Here is the code:
<form action="" method="post">
<fieldset>
<legend>Enter Product Details:</legend>
Product Name:<input type="text" name="productName"><br>
Product Price:<input type="text" name="Price"><br>
<?php
$host="localhost";
$user="root";
$pass="";
$db="computer_shop";
$conn=mysqli_connect($host,$user,$pass,$db) or die ("Couldn't connect");
$sql="SELECT * FROM manufacturer";
$result=mysqli_query($conn,$sql) or die ("Could not execute query!");
if(!$result){
echo"Error with results";
}
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<select name='select'>";
echo"<option value=" .$code.">".$name."</option>" ;
<echo"</select>";
}
echo "<br>";
} else {
echo "0 results";
}
mysqli_close($conn);
?>
<input type="submit" value="Submit">
</fieldset>
</form>
When I attempt this, it doesn't go well. When I load the page, the initial part of the form (with input boxes for name and price are fine), but the drop down list is a mess, and I see the code: "0) { while($row = mysqli_fetch_assoc($result)) { $code=$row["Code"]; $name=$row["Name"]; echo" along with a drop down list showing only $name, and then the submit button. So the HTML file is displaying part of the actual PHP code.
My question is, how do I fix this so that the drop down list will display the values from the mysql database? I have been looking through various sites, trying different things, but I keep getting a similar problem. Should I flip things, and embed the HTML inside a PHP file instead?
In general this code is not a good practice. Make sure that this code is in a .php file and your web server supports php.
Other than that, I think that the following script will solve your problem.
if (mysqli_num_rows($result) > 0) {
//open the select tag before the loop
echo"<select name='select'>";
//populate the select
while($row = mysqli_fetch_assoc($result)) {
$code=$row["Code"];
$name=$row["Name"];
echo"<option value=" .$code.">".$name."</option>" ;
}
//close the select tag after the loop
echo"</select>";
echo "<br>";
} else {
echo "0 results";
}

having trouble getting selected value from php dynamic selection option

I want to show options from my database for users to check, but having trouble getting user's choice.
So, I write two php files,
the first one doing things like: getting data from database, displaying in select option, then submit value by post to and the second php file.
And the second php file just display the recieved value.
Here's the first php file:
<html>
<body>
<form method="post" action="second.php">
<Select name=”select_value”>
<?
//connect to server
$con = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE) or die("Error " . mysqli_error($con));
$query = "SELECT * FROM MYTABLE" or die("Error in the consult.." . mysqli_error($con));
$result = $con->query($query);
//display result in select option
while ($row = mysqli_fetch_array($result)) {
echo "<Option value=".$row['ENTRY_ID']."> ".$row['ENTRY_NAME']."</Option><br>";
}
mysqli_close($con);
?>
</Select>
</form>
</body>
</html>
And the second php file:
<?
$option = isset($_POST['select_value']) ? $_POST['select_value'] : false;
if($option) {
echo $_POST['select_value'];
} else {
echo "not getting value of select option";
exit;
}
?>
If this works fine, I should see the selected value by the second php file, but I keep recieving my echo "not getting value of select option".
There must be something wrong between select option and my recieving file.
Can someone help?
try this double quotes
<Select name="select_value">
instead of <Select name=”select_value”>

Is it possible to Query a Mysql database from a field selected from dropdown menu populated from a Query in php

Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)

Linking 2 SELECT boxes using an SQL Database - PHP

So, im creating a form that will submit data into an SQL database. Ive got 2 select drop downs that hold the data of "Module Code" and "Module Title". In the database a module title will only have one module code e.g Team project(module title) has module code 11COB290.
How can i get it so that when a user selects a given module name OR Module title is will automatically select the correct partner i.e select the right module code thats related to the module name the user has selected without pressing any submit buttons?
The following code is the drop down select boxes and php code i have so far:
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
<td align="center">
<select name='ModuleCode' id='ModuleCode' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module
ORDER BY `ModCode` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[3];
echo "<option name='{$module}'>{$module}</option><br />";
}
?>
</select>
</td>
Unless there is a special reason to do so, why not give a single SELECT box instead of two?
<td align="center">
<select name='ModuleTitle' id='ModuleTitle' style='width:100%;'>
<option>Select...</option>
<?php
//3. Perform database query
$result = mysql_query("SELECT * FROM Module ORDER BY `ModTitle` ASC;", $connection);
if(!$result){
die("Database query failed: " . mysql_error());
}
//4. Use Returned Data
while ($row = mysql_fetch_array($result)) {
$module = $row[2] . ' (' . $row[3] . ')';
$moduleCode = $row[3];
echo "<option value='{$moduleCode}'>{$module}</option>";
}
?>
</select>
</td>
Or otherwise if you would like to keep 2 SELECTs, use AJAX calls. The idea is to define onChange event on each SELECT and in that event, send an AJAX request to a PHP script. The PHP script will request the module code or title and send it back to the AJAX handler. The AJAX handler can then automatically mark as SELECTED the corresponding option in the other SELECT. You might need sometime to research on AJAX and JavaScript if you aren't already experienced with this stuff.
Another idea might be to use the module code as the value for the title SELECT and module title as the value for the code SELECT. For example, title SELECT will be:
<SELECT name="ModuleTitle" id="ModuleTitle" style="width:100%;">
<OPTION>Select...</option>
<OPTION value="123">Title 123</OPTION>
<OPTION value="345">Title 345</OPTION>
<OPTION value="567">Title 567</OPTION>
</SELECT>
Then in the onChange event handler you might do something like this:
var selObj = document.getElementById('ModuleTitle');
var selIndex = selObj.selectedIndex;
document.getElementById('ModuleCode').value = selObj.option[selIndex].text;
By the way, there is no "name" attribute for . It should be "value" instead. Please fix in your code.
Hope it helps!
CAUTION: none of the above code is tested but I hope it works fine

Categories