Separation between name and surname using datalists - php

I'm using a datalist to store all of the names and surnames in that I retrieve from a MySQL database table.
When someone inputs the name and surname of a tutor and clicks "show tutor", showTutor() is called.
<input list="tutorData" name="tutors" id="tutorToShow">
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$name = $row['surname'];
$sName = $row['name'];
?>
<option value="<?php echo "$sName $name" ?>" >
<?php
}
}
?>
</datalist>
<input type="button" value="Weergeven" onclick="showTutor();">
My datalist is filled up and works perfectly. Now: When showTutor is called, so when the button was clicked:
function showTutor(){
var tut = document.getElementById("tutorToShow").value;
}
This gives me something like John Smith or Mary Jane Dough.
What the problem is though, when I reload the shown tutor div with ajax, I need to retrieve that tutor's ID from the database.
So what I'll definitely need is this SQL:
SELECT ID
FROM tutors
WHERE name LIKE '$name%'
AND surname LIKE '$surname%'
Now I just need to separate the name.
In other words, how do I retrieve the ID from a table with columns ID, name, surname, without knowing the separation between name or surname?
John Smith: easy, first word is name, second word is surname
Mary Jane Dough: now what?
I thought of adding a comma that seperates both names, but that's not very stylish.
Another option is to add a column to my database that has both names in one record, but that's a hassle when new tutors need to be added.

Do this before you assign the data into your elements
if (strpos($sName, ' ') != false) {
// if above string position of space isn't false,
// explode the string at the space into an array of
// individual names.
$sName = explode(' ', $sName);
echo $sNames[0];
echo $sNames[1];
// you will need to look at foreach loop and counting the array length
}
Try this.
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$surname = $row['surname'];
$first_names = $row['name'];
if (strpos($first_names, ' ') != false) {
/*
if above string position of space isn't false,
explode the string at the space into an array of
individual names.
*/
$first_name = explode(' ', $first_names); // EG: Paul John
$name1 = $first_name[0]; // Paul
$name2 = $first_name[1]; // John
/*
you will need to look at foreach loop and counting
the array length
*/
}
?>
<option value="<?php echo $name1 . ' ' . $name2 . ' ' . $surname" ?>" >
<?php
}
}
?>
</datalist>

I'm sorry for the delay, #Oli helped me in chat a few weeks ago.
<input list="tutorData" name="tutors" id="tutorToShow">
<datalist id="tutorData">
<?php
$sql = "SELECT name, surname, id FROM tutors ORDER BY surname ASC";
if (!$res = $link->query($sql)) {
trigger_error('error in query ' . $link->error);
} else {
while ($row = $res->fetch_assoc()) {
$name = $row['surname'];
$sName = $row['name'];
$id = $row['id'];
?>
<option value="<?php echo "$sName $name" ?>" data-id="<?php echo $id; ?>">
<?php
}
}
?>
</datalist>
<input type="button" value="Show" onclick="showTutor();">
So basically I've only added a data-id, I then wrote this javascript:
<script>
function showTutor() {
var tut = document.getElementById("tutorToShow").value;
var list = document.getElementById("tutorData");
var length = list.options.length;
var id;
for (var i = 0; i < length; i++) {
var eachTutor = list.options[i].value.toLowerCase();
if (tut === eachTutor) {
id = list.options[i].getAttribute('data-id');
}
}
}
</script>
I now have the id of the tutor, without separating any name. I also post it to a php page with ajax, but that is not relevant to the question.
Thanks again to the ones that helped.

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

Extracting 2 values from different columns from a DB with only 1 Select

Problem solved: This is the solution, thanks to #dont-panic and everyone who helped me !
while($row = mysql_fetch_assoc($get)) {
$option .= '<option id="opcion" value="'.$row['nombre'].'">'
.$row['nombre']
.'</option>';
if (isset($_POST['postre']) && $row['nombre'] == $_POST['postre']) {
$preciodelpostre = $row['precio'];
}
} ?>
as the title say, I'm trying to make a very simple accounting website for my grocery store where I keep my daily sales registered. I already made a form to add new articles in the Database with these table names:
Table: Postres -- postreID(id of the article), nombre(name of the
article), price(price of the article).
I also have another table called "ventas", which is where I wanna store all my sales based on a date criteria, which is already done.
Table: Ventas -- id(sale id), fecha(date of registered sale),
postre_vendido(name of the article sold), ganancia(the article price).
This is my code to register my sales:
<?php
$dbhost = 'db641973975.db.alansete.com';
$dbuser = 'dbo675';
$dbpass = 'dotCos215';
$dbname = 'db643975';
$con = mysql_connect($dbhost,$dbuser,$dbpass);
$db = mysql_select_db($dbname,$con);
$get=mysql_query("SELECT * FROM Postres ORDER BY postreID ASC");
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option id="opcion" value = "'.$row['nombre'].'">'.$row['nombre'].'</option>';
}
?>
<html>
<body>
<?php
$postrevendido = $_POST['postre'];
$preciodelpostre = $_POST['precio'];
if(isset($_POST['agregar'])){
$sql = "INSERT INTO Ventas (id,fecha,postre_vendido,ganancia) VALUES(NULL,NOW(),'$postrevendido','$preciodelpostre')";
$retval = mysql_query($sql);
if(! $retval ) {
die('Could not enter data: <p></p>Agregar otro articulo' . mysql_error());
}
echo "Postre agregado exitosamente!!" . "Volviendo..." . '<p></p>Agregar otro articulo';
mysql_close($conn);
}else {
?>
<form method = "post" action = "<?php $_PHP_SELF ?>">
<p>Producto Vendido
<select name="postre" id="postre">
<?php
echo $option . '<p></p>';
?>
</select>
<input name = "agregar" type = "submit" id = "agregar"
value = "Agregar Venta">
</p>
</form>
<?php }?>
</body>
</html>
At the end it only captures the first 3 columns from(id,fecha,postre_vendido,ganancia) and asigns column "ganancia" a value of 0.
You guys have any idea on how to solve this? Thanks in advance!
The price isn't inserting because you don't have a control in your <form> that has the price in it, but I think the way to fix this is actually not to add such a control. In my opinion you really don't need or want the user to enter the price, you should read it from your product table at the time the form is posted. There are various ways to do that. One way is to set it as you are getting the options to show in the <select>.
while($row = mysql_fetch_assoc($get)) {
$option .= '<option id="opcion" value="'.$row['postreID'].'">'
.$row['nombre']
.'</option>';
if (isset($_POST['postre']) && $row['postreID'] == $_POST['postre']) {
$preciodelpostre = $row['price'];
}
} ?>
If you do it this way, be sure to remove the $preciodelpostre = $_POST['precio']; later in the code; since there is not control named 'precio' on the form, this will overwrite the previous value with null which will end up as 0 in your inserted row.

Get value form same table

I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.

Need help pulling into multiple columns from one database table - mysql_query

Afternoon all,
A very quick question... a friend has set up a form for me using mysql_query. Since he wrote this, I have added an extra column into the database, which I want to pull through into the form.
However I can't seem to get this extra column to appear (labelled Currency). The reason I need it is the query below will pulls back a value and the £ symbol. Because I want to display not only £, but also € prices, I need this extra column to pull through (obviously I will have to remove the £ from the echo below too).
I've tried adding the extra column (Currency) to the code, e.g. "SELECT Room, Currency, Price FROM Spa_Upgrades
but this hasn't worked.
The code is:
<?php
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_array($query2);
echo "<option value='".$result2[0]." £".$result2[1]."pp'>$result2[0] £$result2[1]pp</option>";
}
}
}
Hugely grateful if someone can solve this!
Thanks,
Motley
Alter the query as follows:
SELECT Room, Price, Currency FROM Spa_Upgrades ...
Alter the line beginning echo inside the for loop: replace £ with $result2[2] wherever it appears. (Or if the Currency column doesn't contain the HTML entity for the currency symbol, then replace £ with appropriate code to obtain the symbol from the Currency column entry.)
You also need to add the column to the output... I would also switch to an associative array otherwise if you add a column and its not at the end you have to change all the indexes.
if (isset($id))
{
$query2 = mysql_query("SELECT Room, Price, Currency FROM Spa_Upgrades WHERE Spa_Upgrades.Spa_Id = '".$id."' AND Spa_Upgrades.Id = '".$pack."' order by Spa_Upgrades.Order");
$rows = mysql_num_rows($query2);
if($rows==0) {echo "disabled='disabled'/>";}
else
{
echo "/>";
echo "<option value='Default'>Please Select</option>";
for($i=0; $i<$rows; $i++)
{
$result2 = mysql_fetch_assoc($query2);
$value = $result2['Room'] . ' ' . $result2['Currency'].$result2['Price'].'pp';
echo sprintf('<option value="%s">%s</option>', $value, $value);
}
}
}
Use mysql_fetch_assoc() instead of mysql_fetch_array()
A good practice as well is to separate data retrieving from display logic
Try this:
<?php
$results = array();
if (isset($id))
{
$resource = mysql_query("SELECT room, currency, price FROM Spa_Upgrades
WHERE Spa_Upgrades.Spa_Id = '".intval($id)."' AND Spa_Upgrades.Id = '".intval($pack)."'
order by Spa_Upgrades.Order");
while($row = mysql_fetch_assoc($resource))
$results[] = $row;
}
?>
<select name="..." <?php echo (count($results) > 0 ? '' : 'disabled') ?>>
<option value="Default">Please Select</option>
<?php
foreach($results as $result)
{
$value = $result['room'].' '.$result['currency'].$result['price'].'pp';
echo '<option value="'.htmlspecialchars($value).'">'.htmlspecialchars($value).'</option>'."\n";
}
?>
</select>

How to display mysql records as preselected checkboxes?

I have a table column called post_tags within a table called posts where assigned tags are stored separated by the # symbol. I also have a table called tags where all tag names are stored. I would like to design my database in a more normalized way but for the purpose I am trying to achieve this is the easiest option.
Anyway, I want to display on the screen all the entries from the tags table as checkboxes, so I do:
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query)) {
$tag = $row['name'];
echo "<input type='checkbox' name='tags[]' value='$tag' />\n";
}
Next I want to have the tags that are assigned to a particular post be preselected. For example, if I have a post with the following in it's post_tags column:
party#beaches#dolphins#
I want the "party", "beaches" and "dolphin" checkboxes to be checked by default (while the checkboxes for the other options are unchecked). How can this be done?
try the two results and the in_array() function.
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = explode("#", $post_tags);
while ($row = mysql_fetch_assoc($query)) {
$check = in_array($arr_tags, $row['name'])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
UPDATE
Because of Jeff question on performance, I looked for faster solutions and using isset() is faster so this would do a faster lookup of the values. the array_flip() is 3 time less taxing than in_array():
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = array_flip(explode("#", $post_tags));
while ($row = mysql_fetch_assoc($query)) {
$check = isset($arr_tags[$row['name']])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
The first thing to do is see if there is any existing data. So run that query and put the result of that table cell into lets say $checkedstring if not then put your default string in.
<?php
$checkedstring = "party#beaches#dolphins#";
//Pull from DB if exsists and set $checkedstring to that value
///
$checkeditems = explode ( "#" , $checkedstring);
$checked = array();
foreach($checkeditems as $item)
{
$checked[$item]=true;
}
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query))
{
$tag = $row['name'];
$checkedstatus = '';
if($checked[$tag])
{
$checkedstatus = "checked='checked'";
}
echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n";
}
?>

Categories