I am trying to insert values to a database with a foreach loop. It all works fine but the last element of the array gets inserted twice.
I understand that a reference of a $photo and the last array element remain even after the foreach loop. I am trying to destroy it by using unset($photo) but that does not seem to work, I still get double insert inside my database of the last element.
Can someone explain this to me?
// value of $photos
<?php
$stmt = $conn->prepare(
"SELECT p.*, pt.propertyType
FROM tbl_property p
JOIN tbl_propertyType pt USING (PropertyType_Id)
ORDER BY Price;"
);
$stmt->execute();
?>
<form id = "prop-form" action="../scripts/photo-property.php" method = "POST" enctype="multipart/form-data">
<select name="property">
<?php while($row = $stmt->fetch()){ ?>
<option value="<?php echo $row['Property_Id'];?>"><?php echo $row['propertyType'] . ', ' . 'Price: ' . $row['Price'] . ', ' . $row['BuildingNameStreetNo']
. ', ' . $row['Street'] . ', ' . $row['Town'] . ', ' . $row['Condition']
. ', ' . $row['RoomNo'] . ' Rooms'; ?></option>
<?php } ?>
</select>
<?php $sql = $conn->prepare("SELECT * FROM tbl_Photo");
$sql->execute();
while($row = $sql->fetch()){
echo '<img class="propimg" src=../photos/'. $row['Photo'] . '><br/>';
echo '<input type="checkbox" name="photos[]" value="'. $row['Photo_Id'] . '">';
}
?>
</form>
-------------
// DIFFERENT FILE
// assign the array values from the form
$photos = $_POST['photos'];
// for each photo, bind the param and execute the query
$sql = $conn->prepare("INSERT INTO tbl_propertyphoto (Property_Id, Photo_Id) VALUES (:prop, :photo)");
foreach($photos as $photo) {
$sql->bindParam(':prop', $_POST['property']);
$sql->bindValue(':photo', $photo);
$sql->execute();
}
unset($photo);
Check if your tbl_Photo table hasn't multiple of the same rows.
Try to make the columns Property_Id and Photo_Id UNIQUE together.
In that way you cannot have the same combination twice.
ALTER TABLE tbl_propertyphoto ADD CONSTRAINT UQ_Property_Photo UNIQUE(Property_Id, Photo_Id)
Related
<?php
$get = mysqli_query($conn, "SELECT supplier.*,product.* FROM
supplier,product ORDER BY supplier.supplierid ASC");
$option = '';
while ($row = mysqli_fetch_array($get, MYSQLI_ASSOC)) {
$option .= '<option value = "' . $row['productname'] . '">' .
$row['suppliername'] . '</option>';
}
<label style="margin-left:25px;margin-bottom: 10px; ">Supplier:
</label><select style="margin-bottom:10px ;margin-left: 50px;width:
200px"> <?php echo $option; ?></select>
Hello Maam And Sir I have A problem About that data Output In a Select Box. The thing that happen when i use this code or use two multiple table, the data output also double but if 1 table it is working the way i want. But I don't want to have a dirty codes that why i to put in a single query.
I want to send some information from one php file to another.
I've read about the use of $_SESSION and $_POST, but they're giving me some problems.
My code looks something like this:
<form action="booking.php" method="post">
<select name="bookingflight">
<?php
$query = "SELECT Flight, Name
FROM Airport";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)) {
echo "<option value=\"". $row['Flight'] . ',' . $row['name'] . "\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
}
?>
</select></p>
<input type="submit" value="book flight"/>
</form>
This gives me a dropbox list of all the flights, along with the name of the flights.
If I select an element it's stored in $_POST["bookingflight"] which I can access in booking.php, which is fine.
However, it's given as a string, while I should be able to handle flight and name separately.
Ideally, I'd have two variables, one for flight and one for name, which I can access in booking.php.
How should I do this? With $_SESSION I don't even know how to assign a selected item from the list to a variable.
Alternate Solution: If Flight is unique data
while($row = mysql_fetch_array($result)) {
$flight=$row['Flight'];
$name=$row['Name'];
echo "<option value='$flight'>$flight $name</option>";
}
PHP : booking.php
<?php
$flight=$_POST['bookingflight'];
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT Flight,Name FROM Airport WHERE Flight='$flight'");
$row = mysqli_fetch_array($result);
$name= $row['Name'] ; // Here you get Name of selected Flight
mysqli_close($con);
?>
Or
If your Airport table contains any unique data/id , you can pass that data as option value too
You started this the wrong way...
Give your Airport table a unique primary key (named id, INT, auto-increment) and pass that as a value in generated options:
echo "<option value=\"". $row['id'] ."\">" . $row['Flight'] . ' ' . $row['name'] . "</option>";
Now when you POST your form you get that ID value in booking.php.
Because every flight has a unique ID you can just issue another query and you get your result as an array there:
$query = "SELECT Flight, Name FROM Airport WHERE id = $id";
Put this in your booking.php...
if($_POST)
{
$values = $_POST['bookingflight'];
$val= explode(',',$values);
$_SESSION['flightnumber'] = $val[0];
$_SESSION['flightname'] = $val[1];
}
I have a form with a select box where the user can select pre-existing fields from a database:
<form action='' method='POST' autocomplete='off' enctype="multipart/form-data">
<p><strong>Title and Description:</strong></p>
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"1\">" . $row['title'] ." - " . $row['description'] . "</option>";
$uid = $row['uid'];
$title = $row['title'];
$desc = $row['description'];
}
?>
</select>
...
How can I send all three of those values (separately) to my postback for SQL?
if (isset($_POST['submitted'])) {
//Get params for prepared statements
$startDatec= date("Y-m-d H:i:s", strtotime($_POST['startEventDate']));
$endDatec= date("Y-m-d H:i:s", strtotime($_POST['endEventDate']));
$startTimec=$_POST['startTime'];
$endTimec=$_POST['endTime'];
$recurc=$_POST['recurrence'];
$finalc= date("Y-m-d H:i:s", strtotime($_POST['finalDate']));
...
I have no idea why you would need to send all three values back. Database Keys exist for the reason of being able to identify ALL fields in a record given just a single field, in this case I'm assuming uid. Passing that field alone would allow you to select the other fields in your postback before performing the operation that you intend.
However, it is possible using hidden form fields, although I don't advocate this approach.
<select name='uidtitle' class='chosen-select'>
<option value="0" ></option>
<?php
$result = $mysqli->query("SELECT uid, title, description FROM tblFacilityHrs") or die($mysqli->error);
$cacheArray = array(); // Used to store the information to be used below
while ($row = $result->fetch_array(MYSQLI_ASSOC)){
echo "<option value=\"" . $row['uid'] . "\">" . $row['title'] ." - " . $row['description'] . "</option>";
$cacheArray[] = $row;
}
?>
</select>
<?php
foreach($cacheArray as $k => $v) {
echo '<input type = "hidden" name = "title-' . $v['uid'] . '" value = "' . $v['title'] . '">';
echo '<input type = "hidden" name = "description' . $v['uid'] . '" value = "' . $v['description'] . '">';
}
?>
The hidden form fields will be present for all records in your tblFacilityHrs table. The names are made distinct by appending the uid to the name. You can determine what fields you are interested in in your postback by:
$_POST['title-'.$_POST['uidtitle']]
$_POST['description-'.$_POST['uidtitle']]
I have been reading through, testing, and coming up short from understanding how to create a MySQL statement that matches a column against an array of values...
Here's what I have...
<form id="form" action="index.php" method="post">
<?
$query = "SELECT Interest FROM Interests";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result))
{
echo '<input type="checkbox" name="Interest[]" value="' . $row['Interest'] . '" /> ' . $row['Interest'] . '<br />';
}
?>
<input id="Search" name="Search" type="submit" value="Search" />
</form>
<?
if (isset($_POST['Search']))
{
$InterestMatches = implode(',', $_POST['Interest']);
$query = "SELECT MemberID FROM MemberInterests WHERE Interest IN ( $InterestMatches )";
$result = mysql_query($query) or die(mysql_error());
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
while ($row = mysql_fetch_assoc($result))
{
$ResultingMemberIDs[] += $row['MemberID'];
}
}
?>
And what I always get is the same error...
Unknown column 'WhateverInterest' in 'where clause'
Can someone please tell me what I am doing wrong, what I need to do to correct this?
I suggest echoing out your query, it'll help with debugging. Your query currently looks like:
SELECT MemberID FROM MemberInterests WHERE Interest IN (WhateverInterest,Testing)
As you can see, in the IN the values are unquoted, so they're interpreted as field names. You need to add quotes around each value in the IN.
You can fix it by looping, and adding quotes around each value:
foreach($_POST['Interest'] as &$intrest){
$intrest = "'$intrest'";
}
$InterestMatches = implode(',', $_POST['Interest']);
Or by imploding with "','", and then adding quotes before and after:
$InterestMatches = "'" . implode("','", $_POST['Interest']) . "'";
P.S. You should mysql_real_escape_string each value in $_POST['Interest'] to avoid SQL injections.
Try
$InterestMatches = '"' . implode('","', $_POST['Interest']) . '"';
I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop