Hi I have five (05) comboboxes in the form that fetch values from database but while editing form all comboboxes return no value. I have to select values in the combobox all the time to update form.
Here is my code:
if(isset($_POST['submit']))
{
$fname=validate($_POST['fname']);
$mname=validate($_POST['mname']);
$lname=validate($_POST['lname']);
$gender=validate($_POST['gender']);
$contact=validate($_POST['contact']);
$proid=validate($_POST['proid']);
$distid=validate($_POST['districtid']);
$degid=validate($_POST['degreeid']);
$batchid=validate($_POST['batchid']);
$majorid=validate($_POST['majorid']);
$desg=validate($_POST['designation']);
$inst=validate($_POST['institute']);
$add=validate($_POST['address']);
$userid=$_SESSION['id'];
$img=validate($_POST['featured_img']);
$oldimg=validate($_POST['old']);
$tmp_name = $_FILES['featured_img']['tmp_name'];
$dest = "alumni_images/";
if($img=='') {
$img=$oldimg;
$sql = "UPDATE alumnidata SET firstname='$fname',middlename='$mname',
lastname='$lname',gender='$gender',
address='$add',province_id='$proid',
district_id='$distid',contact='$contact',
degree_id='$degid',batch_id='$batchid',
major_id='$majorid',job_title='$desg',
connected_to='$inst',avatar='$img'
WHERE user_id='$userid'";
if (mysqli_query($con, $sql)) {
move_uploaded_file($tmp_name,$dest.$img);
$msg="Data has been updated successfully";
} else {
$error= "<b>in updating record:</b><br/>" . mysqli_error($con);
}
} else {
$sql = "UPDATE alumnidata SET firstname='$fname',middlename='$mname',
lastname='$lname',gender='$gender',
address='$add',province_id='$proid',
district_id='$distid',contact='$contact',
degree_id='$degid',batch_id='$batchid',
major_id='$majorid',job_title='$desg',
connected_to='$inst',avatar='$img'
WHERE user_id='$userid'";
if (mysqli_query($con, $sql)) {
move_uploaded_file($tmp_name,$dest.$img);
$msg="Data has been updated successfully";
} else {
$error= "<b>in updating record:</b><br/>" . mysqli_error($con);
}
}
Here is my HTML code of one combobox and similar code is for other 04 comboboxes. I have to choose value every time for updating form because if i don't do this, comboboxes return empty value:
<select name="proid" class="form-control" id="provinceid" required="required">
<option value="<?php echo $row['province_id'];?>" disabled selected><?php echo $row['province_name'];?></option>
<?php
$query1="Select * from tblprovinces";
$result1 = mysqli_query($con,$query1);
if(mysqli_num_rows($result1)>0) {
while($row1= mysqli_fetch_assoc($result1)) {
?>
<option value="<?php echo $row1['province_id']; ?>"><?php echo $row1['province_name']; ?></option>
<?php
}
}
?>
</select>
Thanks for helping. My problem is solved. I renamed the primary key field name different.... Three tables had same field name
Related
I am building a custom CMS for myself and its going great but for some reason the system is not inserting a certain field called categories. I have a table called categories and i am able to insert those categories with no problems.
On my addnewpost.php page I have this form field that lets me select an added Category..
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value=""><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
above all that I have this to inset the data into the database in a table called posts...
<?php
if(isset($_POST["Submit"])){
$posttitle = $_POST["posttitle"];
$Category = $_POST["Category"];
$image = $_FILES["image"]["name"];
$target = "../uploads/".basename($_FILES["image"]["name"]);
$posttext = $_POST["postdescription"];
$admin = "phillip";
date_default_timezone_set("Europe/London");
$CurrentTime=time();
$DateTime=strftime("%B-%d-%Y %H:%M:%S",$CurrentTime);
if(empty($posttitle)){
$_SESSION["ErrorMessage"] = "Post title cannot be empty";
redirect_to("addnewpost.php");
} elseif (strlen($posttitle)<10){
$_SESSION["ErrorMessage"] = "Post title should be greater than 10 characters";
redirect_to("addnewpost.php");
} else {
//All is good insert into the database
$sql = "INSERT INTO posts(datetime,title,category,author,image,post)";
$sql .= "VALUES(:dateTime,:postTitle,:categoryName,:adminName,:imageName,:postDescription)";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':dateTime',$DateTime);
$stmt->bindValue(':postTitle',$posttitle);
$stmt->bindValue(':categoryName',$Category);
$stmt->bindValue(':adminName',$admin);
$stmt->bindValue(':imageName',$image);
$stmt->bindValue(':postDescription',$posttext);
$Execute=$stmt->execute();
move_uploaded_file($_FILES["image"]["tmp_name"],$target);
if($Execute){
$_SESSION["SuccessMessage"]="Post with id : ".$conn->lastInsertId()." Added Successfully";
redirect_to("addnewpost.php");
} else {
$_SESSION["ErrorMessage"]="Something went wrong. Try again";
redirect_to("addnewpost.php");
}
}
}
?>
Here is a screengrab showing that the category fields are empty. I do have display errors enabled but none are showing up. Any thoughts appreciated...
Thank you Nigel and Felippe. I just took out the option value so it's just this instead...
<option><?php echo $CategoryName; ?></option>
That's made it all work perfectly. Been looking at this for hours as well.
Thank you both.
<select name="Category" id="categorytitle" class="form-control">
<?php
$sql = "SELECT id,title FROM category";
$stmt = $conn->query($sql);
while ($DataRows = $stmt->fetch()){
$id = $DataRows["id"];
$CategoryName = $DataRows["title"];
?>
<option value="<?php echo $CategoryName; ?>"><?php echo $CategoryName; ?></option>
<?php } ?>
</select>
This is more like it
I creating an inventory web-base system by using php and php myadmin (InnoDB). I want to insert the value in inventory when I inserting the record, I can see the data of the (FK) in the dropdown but when I submit the form the data to the db, it returns as no input value in the field and the dropdown not there anymore. Is the way I'm using the foreign key in the dropdown wrong?
I have a table that contains multiple foreign keys.
Table Inventory(
id (pk),
name,
condition_(fk),
producttype (fk))
Table condition_type(
condition_ (pk))
Table producttype(
producttype(fk))
<?php
// Include config file
require_once "../config.php";
// Define variables and initialize with empty values
$name = $condition_ = $producttype = "";
$name_err = $condition_err = $producttype_err = "";
$sql2 = "SELECT * FROM condition_type";
$sql4 = "SELECT * FROM producttype";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate name
$input_name = trim($_POST["name"]);
if(empty($input_name)){
$name_err = "Please enter a name.";
}else{
$name = $input_name;
}
// Validate condition
$input_condition = trim($_POST["condition_"]);
if(empty($input_condition)){
$condition_err = "Please choose the condition.";
} else{
$condition_ = $input_condition;
}
// Validate producttype
$input_producttype = trim($_POST["prodcuttype"]);
if(empty($input_producttype)){
$producttype_err = "Please enter the product type..";
} else{
$producttype = $input_producttype;
}
// Check input errors before inserting in database
if(empty($name_err) && empty($condition_err) && empty($producttype_err)){
// Prepare an insert statement
$sql = "INSERT INTO inventory (name, condition_, producttype) VALUES (?, ?, ?)";
if($stmt = $mysqli->prepare($sql)){
// Bind variables to the prepared statement as parameters
$stmt->bind_param("sss", $param_name, $param_condition, $param_producttype);
// Set parameters
$param_name = $name;
$param_condition = $condition;
$param_producttype = $producttype;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Records created successfully. Redirect to landing page
header("location: ../application");
exit();
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
$stmt->close();
}
// Close connection
$mysqli->close();
}
?>
-------> This is the form
<div class="form-group <?php echo (!empty($condition_err)) ? 'has-error'
: ''; ?>">
<label>Condition</label>
</br>
<select id="condition_" name="condition_" class="form-control" value="<?
php echo $condition_ ;?>">
<option>Please Select Product Condition</option>
<?php
if($result2 = $mysqli ->query($sql2)){
while($row = $result2->fetch_array()){
echo "<option value=".$row['condition_'].">" .$row['condition_']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $condition_err;?></span>
</div>
<div class="form-group <?php echo (!empty($producttype_err)) ? 'has-
error' : ''; ?>">
<label>Product</label>
</br>
<select name="producttype" class="form-control" value="<?php echo
$producttype ;?>">
<?php if($result4 = $mysqli ->query($sql4)){
while($row = $result4->fetch_array()){
echo "<option value=".$row['producttype'].">" .$row['producttype']. "
</option>";
}
}
?>
</select>
<span class="help-block"><?php echo $manufacturer_err;?></span>
</div>
So when I submit it return as the condition and producttype are empty. I think the error is because of
}
// Close connection
$mysqli->close();
}
statement that already close. But I don't know to place it.
PHP Warning: mysqli::query(): Couldn't fetch mysqli in /home/my-path/application/create_new.php on line 173
You should debug the html form first by right click with 'Inspect element' and make sure that the 'Select' value is getting?
Through hours of research and looking through code in questions submitted on this site, I was finally able to get the select options (dropdowns) to pull data from my database tables into the dropdown lists on my html form.
However, my issue is that when the fields on the form were inputs they inserted the new information into the database just fine. Unfortunately, now that I've implemented the dropdown lists as part of the form, none of the information from the form inserts into the database anymore. Clicking on the 'submit' button returns the response that it was successful, but when I check the table in the database, the new information is not there.
I'm sorry I haven't been able to figure this piece of functionality out by myself. I noticed my last question received negative feedback, so I'm leary to even submit this one, but I really need some help.
Will you please look through the following code and let me know what I'm missing or have coded incorrectly? I just need to know what I need to do to make the selected values from the dropdown lists insert into the 'dvd' table and 'categoryname' and 'genretype' fields, respectively.
<?php
session_start();
//include the header
include ('../main/header.php');
// Check if the form has been submitted.
if (isset($_POST['submitted'])) {
require_once ('../../../mysqli_connect.php'); // Connect to the db.
$errors = array(); // Initialize error array.
// Check for a first name.
if (empty($_POST['title'])) {
$errors[] = 'You forgot to enter a title.';
} else {
$title = mysqli_real_escape_string($dbc, $_POST['title']);
}
// Check for a category.
if (empty($_POST['numavail'])) {
$errors[] = 'You forgot to enter quantity purchased.';
} else {
$numavail = mysqli_real_escape_string($dbc, $_POST['numavail']);
}
// Check for a category.
if (empty($_POST['categoryname'])) {
$errors[] = 'You forgot to enter a category.';
} else {
$categoryname = mysqli_real_escape_string($dbc, $_POST['categoryname']);
}
// Check for a genre.
if (empty($_POST['genretype'])) {
$errors[] = 'You forgot to enter a genre.';
} else {
$genretype = mysqli_real_escape_string($dbc, $_POST['genretype']);
}
if (empty($errors)) { // If everything's OK.
// Add the movie to the database.
// Check for existing record.
$query = "SELECT id FROM dvd WHERE title='$title'";
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
if ($result) { // If it ran OK.
echo "<p><b>Success! The new movie has been added.</b></p>";
echo ('<p><div style="margin-top:30px;">');
echo ('<span style="float:left;">');
echo ('<FORM METHOD="LINK" ACTION="../dvd/index.php"><INPUT TYPE="submit" VALUE="Back to DVDs" STYLE="margin:0px 15px 0px 0px;"></form></span></div></p>');
echo ('<br style="clear:both;"></br>');
exit();
} else { // If it did not run OK.
$errors[] = 'The movie could not be added due to a system error. We apologize for any inconvenience.'; // Public message.
$errors[] = mysqli_error($dbc); // MySQL error message.
}
} else { // Title is already taken.
$errors[] = 'The movie title entered already exists.';
}
} // End of if (empty($errors)) IF.
mysqli_close($dbc); // Close the database connection.
} else { // Form has not been submitted.
$errors = NULL;
} // End of the main Submit conditional.
// Begin the page now.
if (!empty($errors)) { // Print any error messages.
echo '<p class="error">The following error(s) occurred:<br />';
foreach ($errors as $msg) { // Print each error.
echo "$msg<br />";
}
echo '</p>';
echo '<p style="color:red; font-weight:bold;"><em>Please try again.</em></p></br>';
}
// Create the form.
?>
<h1>Add a Movie</h1>
<h2>Please complete all of the fields below:</h2>
<form action="../dvd/add.php" method="post">
<p>Title: <input type="text" name="title" size="15" maxlength="15" value="<?php echo $_POST['title']; ?>"></p>
<p>Quantity Purchased: <input type="text" name="numavail" size="15" maxlength="30" value="<?php echo $_POST['numavail']; ?>"></p>
<p>
<?php
include ('../../../mysqli_connect.php'); // Connect to the db.
$ddlquery = "SELECT categoryname FROM category ORDER BY categoryname ASC";
$ddlresult = mysqli_query($dbc, $ddlquery) or die("Bad SQL: $ddlquery");
echo 'Category: <select name="categoryname" size="1">';
while($ddlrow=mysqli_fetch_array($ddlresult, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow['categoryname']."'>" . $ddlrow['categoryname'] . "</option>";
}
echo "</select>";
?>
<p>
<?php
$ddlquery2 = "SELECT genretype FROM genre ORDER BY genretype ASC";
$ddlresult2 = mysqli_query($dbc, $ddlquery2) or die("Bad SQL: $ddlquery");
echo 'Genre: <select name="genretype" size="1">';
while($ddlrow2=mysqli_fetch_array($ddlresult2, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow2['genretype']."'>" . $ddlrow2['genretype'] . "</option>";
}
echo "</select>";
?>
<p>
<input type="submit" name="submit" value="Submit">
<input type=reset value=Reset>
<input type="hidden" name="submitted" value="TRUE"></p>
</form>
<?php
// Include footer.php
include("../../includes/footer.php");
?>
You forgot to actually run the insert into database
$result = mysqli_query($dbc, $query);
if (mysqli_num_rows($result) == 0) { // if there is no such movie title
$query = "INSERT INTO dvd (title, numavail, categoryname, genretype)
VALUES ('$title', '$numavail', '$categoryname', '$genretype')";
// Make the query.
$result = mysqli_query($dbc, $query); // <---- ADD HERE
if ($result) { // If it ran OK.
....
this is my php code. hire is a problem i use check box selection and insert data in my database. but it insert data by foreach loop. so when press ok if data successfully insert then for 3 selection it say
successfully register
successfully register
successfully register
but i want it say only once successfully register
<?php
$db=require "script_database/connect.php";
$query = "SELECT * FROM course";
$query1="select * from selection where student_id='1229CSE00241' and semester='FALL2015' ";
$key=mysql_query($query1);
if(mysql_num_rows($key)>0)
{
echo "you already selected courses for registration";
}
else if($_POST['buy']==''){
echo "<h2><center>You didn't select any courses</h2></center>";
}
else{
foreach($_POST['buy'] as $item) {
$query = "SELECT * FROM course WHERE id = $item
";
if ($r = mysql_query($query)) {
while ($row = mysql_fetch_array($r)) {
$student_id="1229CSE00241";
$id=$item;
$course_id=$row['course_id'];
$course_title=$row['course_title'];
$course_credits=$row['course_credits'];
$course_status=$row['course_status'];
$semester="FALL2015";
}
} else {
print '<p style="color: blue">Error!</p>';
}
{
$insert_query="insert into selection(student_id,semester,course_id,course_title,course_credits,course_status,date_time) values ('$student_id','$semester','$course_id','$course_title','$course_credits','$course_status',NOW())";
}
//here is my problem
//it repeat every time when insert data but i want to make it only once
if(mysql_query($insert_query))
{
echo "successfully register";
}
else
echo "problem show";
}
}?>
Before you start your foreach loop set a flag like:
$error = false;
Then in your loop
if(!mysql_query($insert_query))
{
$error =true;
}
And after the loop has closed
if($error){
echo "problem show";
}else{
echo "successfully register";
}
I'm having trouble inserting data into a table.
I have the following tables: track (id, tracktitle), album (id, albumtitle), composer (id, composername), albumtrack (PRIMARY: trackid, albumid, composerid).
My PHP page allows you to add a track and then select the album and composer connected with it. It adds the track to the tracktable okay but it won't add it to an album.
I keep looking around for how to do it and I keep getting a bit lost.
Can anyone tell me how I should be correctly doing this?
Thanks
if (isset($_POST['tracktitle'])):
// A new track has been entered
// using the form.
$cid= $_POST['cid'];
$tracktitle = $_POST['tracktitle'];
$albs = $_POST['albs'];
if ($cid == '') {
exit('<p>You must choose an composer for this track. Click "Back" and try again.</p>'); }
$sql = "INSERT INTO track, albumtrack SET
track.tracktitle='$tracktitle', albumtrack.albumid='$albs', albumtrack.composerid='$cid' " ;
if (#mysql_query($sql)) {
echo '<p>New track added</p>';
} else {
exit('<p>Error adding new track' . mysql_error() . '</p>');
}
$trackid = mysql_insert_id();
if (isset($_POST['albs'])) {
$albs = $_POST['albs'];
} else {
$albs = array();
}
$numAlbs = 0;
foreach ($albs as $albID) {
$sql = "INSERT IGNORE INTO albumtrack
SET albumtrack.trackid='$trackid', albumtrack.albumid='$albs', albumtrack.composerid='$cid'";
if ($ok) {
$numAlbs = $numAlbs + 1;
} else {
echo "<p>Error inserting track into album $albID: " .
mysql_error() . '</p>';
}
}
?>
<p>Track was added to <?php echo $numAlbs; ?> albums.</p>
<p>Add another track</p>
<p>Return to track search</p>
<?php
else: // Allow the user to enter a new track
$composers = #mysql_query('SELECT id, composername FROM composer');
if (!$composers) {
exit('<p>Unable to obtain composer list from the database.</p>');
}
$albs = #mysql_query('SELECT id, albumtitle FROM album');
if (!$albs) {
exit('<p>Unable to obtain album list from the database.</p>');
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<p>Enter the new track:<br />
<textarea name="tracktitle" rows="1" cols="20">
</textarea></p>
<p>Composer:
<select name="cid" size="1">
<option selected value="">Select One</option>
<option value="">---------</option>
<?php
while ($composer= mysql_fetch_array($composers)) {
$cid = $composer['id'];
$cname = htmlspecialchars($composer['composername']);
echo "<option value='$cid'>$cname</option>\n";
}
?>
</select></p>
<p>Place in albums:<br />
<?php
while ($alb = mysql_fetch_array($albs)) {
$aid = $alb['id'];
$aname = htmlspecialchars($alb['albumtitle']);
echo "<label><input type='checkbox' name='albs[]' value='$aid' />$aname</label><br />\n";
}
?>
Your insert sentence is wrong:
Try this:
$sql = "INSERT IGNORE INTO albumtrack (trackid, albumid, composerid) values " .
"($trackid, $albs, $cid)";
Assuming your IDs are numeric.
Beware of SQL Injections when you inject non-sanitized values you get from your request.
Beside's Pablo's corrected way of writing the query. I also notice you are trying to insert into two tables at once with:
$sql= "INSERT INTO track, albumtrack"
MySQL does not allow inserting into two tables at once.