I was wondering if anyone could help, I am creating an update product form which is showing results of data already in the database. I want to display all the checkbox categories and have the ones that have already been selected as checked so the user can easily select and change.
I know I am overcomplicating the code below but I am really no sure how to go about this. The code below currently selects all the categories and displays them as checkboxes but I cant get it to display the ones the user has already selected and saved to the db as checked. Also I am using MySQL original version not the improved one which I know I should be but If anyone could help I would really appreciate it Thanks Louise.
<?php
$query = "SELECT * FROM category, catid_productid WHERE catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$result = mysql_query($query);
$query = "SELECT * FROM category, catid_productid WHERE category.cat_id = catid_productid.cat_id AND catid_productid.product_id ='$product_id' ORDER BY product_id ASC";
$selected_result = mysql_query($query);
$selected_array = array($selected_result);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id;
if (isset($_GET['product_id']) && in_array($selected_array['$selected_result'], $selected_array)) {
echo 'checked="checked"';
}
echo " /></li>'";
}
?>
form field:
<div class="field-row ">
<label for="categories"> Categories:<?php
if (isset($required) && in_array('category', $required)) { ?>
<span class="warning">*</span><?php } ?></label>
<div class="fields">
<ul>
<?php
$query = "SELECT * FROM category ORDER BY title ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$title= $row ['title'];
$cat_id= $row ['cat_id'];
echo '<li><label for="category-'.$cat_id.'" id="labelleft">'.$title.'</label>';
echo '<input name="category[]" id="category-'.$cat_id.'" type="checkbox" class="formbox" value="'.$cat_id.'" /></li>';
}
?>
</ul>
</div>
</div>
inserting it into the database
if($result) {
$product_id = mysql_insert_id();
foreach ($category as $cat_id)
{
// connect to mysql database
mysql_query("INSERT INTO catid_productid (cat_id, product_id) VALUES ('$cat_id', '$product_id')");
}
I don't know if you store checked-or-not information in your DB but I do spot mis-quotation here ..
Try changing this
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id;
To
echo '<input name="category[]"
id="category-'.$cat_id.'"
type="checkbox" class="formbox" value="'.$cat_id.'"';
AND this
echo " /></li>'";
to
echo ' /></li>';
Related
i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert
I am trying to create a form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and finally by event title, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, but it seems to output every single event from the database no matter what I type in the search field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value = '$venueID'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<input type="checkbox" name="S_venueName">
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catID'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
searchfunction.php file
<?php
$count = 0;
include 'database_conn.php';
$venuename = $_REQUEST['venueName']; //this is an integer
$catdesc = $_REQUEST['catdesc']; //this is a string
$Price = $_REQUEST['S_price'];
$EventT = $_REQUEST['S_EventT'];
$sql = "select * FROM te_events WHERE venueID LIKE '%$venuename%' OR catID LIKE '%$catdesc%' OR eventPrice LIKE '%Price%' OR eventTitle LIKE '%$EventT%'";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo $row['eventTitle'];
echo $row['eventDescription'];
echo $row['venueID'];
echo $row['catID'];
echo $row['eventStartDate'];
echo $row['eventEndDate'];
echo $row['eventPrice'];
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
The query should be
$sql = "select * FROM te_events
WHERE (venueID LIKE '%$venuename%'
OR catID LIKE '%$catdesc%'
OR eventPrice LIKE '%$Price%'
OR eventTitle LIKE '%$EventT%')
;
To get values from the form submitted with method POST we use $_POST to access form data and not $_REQUEST:
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
That was about your problem - now some important notes:
Do not use mysql extension as it's deprecated. Read this official documentation.
Use mysqli and prevent SQL injections by using prepared queries and parameters like in official documentation again.
Since you are matching on any fields surrounded by wildcards, if any of the fields are blank, then the MySQL query will match all rows.
Also, you need to prevent MySQL injection. Otherwise, your MySQL table will eventually be hacked.
By the way, the code eventPrice LIKE '%Price%' is invalid and is missing a dollar sign.
Lastly, the mysql extension has been deprecated. I would recommend using mysqli instead as it is fairly similar.
I am trying to allow users to select restrictions from my database by using 3 drop down boxes. I have set them up and I have connected to my database. However, once the user hits the submit button, I can't get data to be displayed in a table. Here is my code:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
I can't get the data to be displayed in a table at all. I have tried multiple ways, but I am still getting errors. To ensure that I am connected to my database, I used var_dump($row) to make sure, and that worked okay. So that is not the problem. Does anyone have any idea what is wrong with my code?
When you retrieve the data from your result set you're fetching it as an object:
while ($row = $result->fetch_object()){
But when you come to display it, you refer to it as an array:
echo "<tr><td>";
echo $row['Year']; // array syntax.
You should be using object syntax:
echo "<tr><td>";
echo $row->Year; // object syntax.
If you check your error logs you should see a lot of messages to this effect.
I have a form that allows the user to add or remove users from a job by using checkboxes. At the moment the engineer's names etc are stored in a table called 'users' and they are identified by their user type, engineers. The checkboxes on the form are created by using a while loop to display a mysql query. This is done so that new users can be added to the database via a webpage at a later date and their name will automatically be added to the list of available engineers. To add an engineer to a job their name is simply ticked and the form submitted.
This works well but I would like the user to be able to add or remove users by checking and unchecking boxes on another form but I can't think for the life of me how to do this.
The users assigned to a job are stored in a many-to-many table called calls_engineers which has 3 fields
id_ce (unique id)
call_ce (id of job, a foreign key)
engineer_ce (id of engineer, a foreign key)
The engineer_ce is the users primary key in the 'users' table which is 'id'.
The code I have so far is...
<? $sql = "SELECT * FROM calls_engineers WHERE call_ce = '$diary_id'";
$result = mysql_query($sql) or die(mysql_error());
$row2 = mysql_fetch_array($result);
$sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){ ?>
<div style="width:70px; float:left">
<?
if($row2['engineer_ce'] == $row['id']){
?>
<input type="checkbox" name="engineer[]" checked="checked" value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name'];
} else { ?>
<input type="checkbox" name="engineer[]" value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name'];
}?>
</div>
<?
}
?>
All this does is create checkboxes for each user which is an engineer but it doesn't check them if the user is assigned to the job.
Any help will be greatly appreciated
You never loops the calls_engineers table. Using
$row2 = mysql_fetch_array($result);
Will not actually find all assignments for the engineer. Now check every single engineer if this is included in current job:
<?
$sql = "SELECT * FROM users WHERE type = 'engineer' ORDER BY first_name";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)){ ?>
<div style="width:70px; float:left">
<input type="checkbox" name="engineer[]" <?
$result2 = mysql_query("SELECT * FROM calls_engineers WHERE call_ce = '".mysql_real_escape_string($diary_id)."' AND engineer_ce = ".$row['id']);
if(mysql_num_rows($result2) > 0) echo 'checked="checked"';
?> value="<? echo $row['id']; ?>" />
<? echo ' '.$row['first_name']; ?>
</div>
<? } ?>
I have a user database which I want the admin to be able view users. I want the admin to be able to sort the users by different fields. (E.g first name or surname).
My problem:
Is that it wont sort. Im trying to do it using a drop down box and a submit button. I have have tried the Sql in phpMyAdmin to make sure the statement is correct which it is. I have also added a or die to make sure its not a mysql error. Im getting no errors its just not sorting. I have also tried echoing out the drop down to make sure the right value is being added to the variable.
code:
HTML drop down
<form action="View_users.php" enctype="multipart/form-data" name="sort" id="sort" method="post" align="right">
<label>
<select name="sortdropdown" id="sortdropdown">
<option value="<?php echo $sortby; ?>"><?php echo $sortby; ?></option>
<option value="name">First Name</option>
<option value="surname">Surname</option>
<option value="email">Email</option>
<option value="signupdate">Date</option>
</select>
</label>
<label>
<input type="submit" name="button" id="button" value="Sort" />
</label>
</form>
logic:
$sortby = "";
if (!isset($_POST['sortdropdown'])) {
$sortby = "surnname";
}else{
$sortby = mysql_real_escape_string($_POST['sortdropdown']);
}
// This block grabs the whole list for viewing
$product_list = "";
$counter = 0;
$sql = mysql_query("SELECT * FROM users ORDER BY '$sortby' ASC") or die(mysql_error());
$productCount = mysql_num_rows($sql); // count the output amount
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$counter++;
$id = $row["id"];
$email = $row["email"];
$name = $row["name"];
$surname = $row["surname"];
$lastlogin = $row["lastlogin"];
$signupdate = $row["signupdate"];
if (is_float($counter/2)) {$class = "#CCCCCC"; }
else {$class = "white";}
$product_list .= '<tr bgcolor="'.$class.'">
<td>'.$surname.'</td>
<td>'.$name.'</td>
<td>'.$email .'</td>
<td>View More</td></tr>';
}
} else {
$product_list = "There are no users in the system yet";
}
Thanks
The comments are correct, you should be using back ticks `$sortby` instead of '$sortby'
The reason is - single quotes are used to wrap values in MySQL, which is not what you want. You're passing the name of a table column, so you use back ticks because they are used to wrap table column names.