How to insert into a table after doing a select in a form - php

I have a PHP form that is collecting information and writing it to a database and it is working correctly. I have one field that is a select to choose entries from an existing table. I would like that result to be inserted into a different table but can't get the insert into to work. I would like to insert the FacilityName field chosen in the select to table2.
$result = mysql_query("SELECT * FROM facility");
print "<select name=\"Id\" > \n";
while ($row = mysql_fetch_array($result)){
$Id = $row['Id'];
$FacilityName = $row['FacilityName'];
print "<option value=$Id>$FacilityName\n";

Related

Changing cell value based on another cell

I am working on a simple php app where I store employees data.
Basically, I have in MySQL few tables, one of them is Employees where I have many columns like name, position, costcenter, manager, etc...
Via php I am able to change the records in the table (simple CRUD).
What I want to achieve is when I change Position based on this Cost Center to be changed.
I have a separate table (CostCenters.sql) with all positions and their cost centers with a structure like this:
CostCenter
Position
124
Engineer
199
Manager
In my edit.php I am taking the positions from this table like this:
echo "<select name='position' required>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT position
from employees
WHERE id = $id
UNION SELECT jobtitle from costcenters");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['position'] ."'>"
.$data['position'] .
"</option>";
}
echo "</select>";`
In the same file for cost centers I have:
echo "<select name='costcenter' required>";
//echo "<option disabled selected>-- Избери --</option>";
include "dbConn.php";
$records = mysqli_query($db,
"SELECT costcenter, POSITION
FROM employees
WHERE id = $id
UNION ALL SELECT constcenternr, jobtitle
FROM costcenters ");
while($data = mysqli_fetch_array($records))
{
echo "<option value='".$data['costcenter'] ."'>"
.$data['costcenter'] . "-" .$data['POSITION'] . "
</option>";
}
echo "</select>";`
And my update query is very simple:
UPDATE employees
SET costcenter ='$costcenter',idcard ='$idcard',
personalnr ='$personalnr',position ='$position';
The question is how to make it when I update the record for Position to automatically changed also the CostCenter based on the value corresponding from (CostCenters.sql).
I have tried editing the select query for edit.php to union also the records from (CostCenters.sql) but had no success.
Here is my select query: (simple)
$result = mysqli_query($mysqli,
"SELECT * FROM employees WHERE id ='$id' ");
while($data = mysqli_fetch_array($result))
My first trial was to modify update query in this way:
UPDATE employees
SET costcenter =
(select costcenternr
from CostCenters
where ****),idcard ='$idcard',
personalnr = '$personalnr',position = '$position';
Frankly speaking, my SQL skills are not enough to complete this query

Check values from shuffled column

I have created an exercise on which one column has words and the second column has the pronounce.
The second column is shuffled.
The code which shows the results is:
echo "<table><tr><td>ideogram</td><td>Pinyin<td>";
while($row = pg_fetch_array($ideo_results)){
$pinyin_query = "select id, pinnin from temp_match where ideogram = '".$row['ideogram']."'";
$pinyin_results = pg_query($cn, $pinyin_query);
while($line = pg_fetch_array($pinyin_results)){
echo "<tr><td><input type=button name=".$row['id']." value='".$row['ideogram']."'></td><td><input type=button name=".$line['id']." value='".$line['pinnin']."'></td><td>";
}
}
echo "</table>";
How can I get the values from 2 selected buttons in order to check if the user choose the correct or the wrong ?
The ID is the name for all the buttons BUT the name is unique

Sending options from html select box into database

Update: I’m now getting an error telling me that roomID is null and this is why it’s not going into the database. Can you see why it would be null when it should be the option that the user selects in the select box?
I'm working on a hotel booking system as an exercise. I am trying to make a form that will insert a new booking into the database. I have the customer and room IDS in the mySQL database and I have put them into HTML select boxes for the user to select an option.
This works fine until I try to save the new booking to the database. I don't get any errors and it tells me the booking has been saved on my page but if I go into the database it hasn't been saved. I have tried inserting the customerID and roomID values from text boxes so just typing it in instead of the drop down menu and that inserts into the database just fine.
I'm pretty sure the problem is something to do with getting the value out of the select box and into the POST variable but I'm not 100% sure. I've only been coding for 6 months so I don't really know what I'm doing! I've tried to figure it out by looking at other examples on here but nothing seems to work.
Here's my code:
Getting the data to fill the select boxes:
//Locate room names
$query = $query = 'SELECT `roomID` FROM `room`';
$result2 = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result2);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result2);}
//Locate customerIDs
$query = $query = 'SELECT `customerID` FROM `customer`';
$result = mysqli_query($DBC,$query);
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_assoc($result);}
Creating Select boxes:
<form method="POST" action="newbooking.php">
<p>
<label for="customerID">Customer ID: </label>
<?php
echo "<select name='customerID'id='customerID' input type='number'>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='customerIDselect'>" . $row['customerID'] . "</option>";
//customerID
$customerID = cleanInput($_POST['customerIDselect']);
}
echo "</select>";
?>
</p>
<p>
<label for="rooms">Room (name, type, beds): </label>
<?php
echo "<select name='roomID'id='roomID' input type='number'>";
// output data of each row
while($row = $result2->fetch_assoc()) {
echo "<option value='roomIDselect'>" . $row['roomID'] . "</option>";
//roomID
$roomID = cleanInput($_POST['roomIDselect']);
}
echo "</select>";
?>
</p>
Inserting data into database:
//save the customer data if the error flag is still clear
if ($error == 0) {
$query = 'INSERT INTO `bookings` (`customerID`,`roomID`,`checkin`,`checkout`, `extras`) VALUES (?,?,?,?,?)';
$stmt = mysqli_prepare($DBC,$query); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $customerID, $roomID, $checkin, $checkout, $extras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}

Insert HTML inside of $db->Execute command

I have this command:
$result = $db->Execute("select id,name,description,requirements,display_condition from works order by id");
And I want to insert < td > INSIDE of the command, that way it enters all of the above select information into a table box.
I tried inserting echo "< td >"; right before the command, but it only creates ONE table box.
Screenie displaying my code and what is happening:
You need to execute something like this:
echo "<table border='1'>";
$query = 'SELECT id, name, description, requirements FROM works ORDER BY id';
$rows = $db->query($query, PDO::FETCH_OBJ);
while( $entry = $rows->fetch() ) {
echo "<tr>"
."<td>".$entry->id."</td>"
."<td>".$entry->name."</td>"
."<td>".$entry->description."</td>"
."<td>".$entry->requirements."</td>"
."</tr>";
}
echo "</table>";
This code allows to populate the data from the DB into a table.
BTW, if you have to skip some rows in the DB by analyzing the "display_condition" field, you would better do it in the SQL query. (I mean in the "$query = ..." line)

Exclude certain columns from SHOW COLUMNS mysql

I have this query: SHOW COLUMNS FROM mash which works fine in my while loop for building a select element made from table column names. But in my table i have "id" and "tstamp" which i dont want in the select element, is this possible to exclude these columns?
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result)) {
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";
PHP Way:
Use a continue in the while loop, when those fields are fetched, like this:
echo "<form action='".$_SERVER['PHP_SELF']."' method='get'>";
connectDB();
$result = mysql_query("SHOW COLUMNS FROM mash") or die(mysql_error());
echo '<select name="column" class="column">';
while ($row = mysql_fetch_array($result))
{
if($row[0] == 'id' || $row[0] == 'tstamp')
continue;
echo "<option value='".$row[0]."'>".ucwords($row[0])."</option>";
}
closeConn();
echo '</select>';
echo "</form>";
This will just skip the id and tstamp fields and process all others. continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.
MySQL Way:
Remove those fields in the query like this:
SHOW COLUMNS FROM mash WHERE Field NOT IN ('id', 'tstamp');
Yes, it's possible. Instead of using SHOW COLUMNS use INFORMATION_SCHEMA.
INFORMATION_SCHEMA is the ANSI way of extracting metadata from a relational database. In MySQL you can use:
$sql = "select column_name from information_schema.columns c " +
" where c.table_schema = 'db_name' " +
" and c.table_name='table_name' " +
" and c.column_name like 'name%'";
Information Schema has the advantage that is SQLANSI compliant. You can use it in MySQL, PostgreSQL, SQLServer and other relational databases.
You can use LIKE operator.
SHOW COLUMNS FROM mash LIKE "name%"
To see just the "Collation" column that shows up in SHOW FULL COLUMNS from tablename for just one field, it's:
select COLLATION_NAME from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';
Ddrop the fieldname in the where, if you want to see that column for all field names.
To see all possible column names that show up from SHOW FULL COLUMNS so that you can select what you want:
select * from information_schema.columns
where TABLE_SCHEMA = 'tableschemaname' and TABLE_NAME = 'tablename' and COLUMN_NAME = 'fieldname';

Categories