I have a table naming related_products,
Where
products_id is the main product.
and related_products_ids consist of product ids related to the main product.
--------------------------------------------
| products_id | related_products_ids |
| -----------------------------------------
| 1 | 2 |
| -----------------------------------------
| 1 | 4 |
| -----------------------------------------
| 1 | 3 |
-------------------------------------------
I have checkboxes,
<input value="2" type="checkbox" name="rp_product[]" id="in-category2"> Microsoft IntelliMouse Pro 2
<input value="3" type="checkbox" name="rp_product[]" id="in-category3"> Microsoft IntelliMouse Pro 3
<input value="4" type="checkbox" name="rp_product[]" id="in-category3"> Microsoft IntelliMouse Pro 4
The checkboxes are generated by php,
<?php
echo '<ul id="categorychecklist" class="list:category categorychecklist form-no-clear">';
global $wpdb;
$sql = "SELECT related_products_ids FROM ".TABLE_RELATED_PRODUCTS." where products_id = '" . (int)$HTTP_GET_VARS['pID']."'";
$result = mysql_query($sql);
$rps = array();
while($row = mysql_fetch_assoc($result)) {
$rps[]=$row["related_products_ids"];
}
$rp_sql = "select products_id, products_name from ".TABLE_PRODUCTS_DESCRIPTION." where products_id !='" . (int)$HTTP_GET_VARS['pID']."' order by products_name";
$rp_1 = mysql_query($rp_sql);
while($rp_2 = mysql_fetch_array($rp_1)) {
$checked = '';
if (in_array($rp_2['products_id'], $rps)) $checked = " checked";
echo "<li id=\"category-".$rp_2['products_id']."\" class=\"popular-category\"><label class=\"selectit\"><input value=\"".$rp_2['products_id']."\" type=\"checkbox\" name=\"rp_product[]\" class=\"rp_item\"" . $checked . "> <span>".$rp_2['products_name']."</span></label></li>";
}
mysql_free_result($rp_1);
echo '</ul></div></div>';
?>
And i use this code to save the checked checkboxes to the related_products table,
for ($i=0; $i<count($_POST['rp_product']); $i++)
{
$check_val1 .= $_POST['rp_product'][$i] .","; //gather data
}
$check_val = trim($check_val1, ','); //clean last ,
unset($check_val1); //flush
$insert_rp_ids1 = explode(',', $check_val);
foreach($insert_rp_ids1 as $id){
$rps_each2 = array('products_id' => $products_id, 'related_products_ids' => $id);
$wpdb->insert(TABLE_RELATED_PRODUCTS, $rps_each2);
}
What i want is to delete a particular id under related_products_ids column when the checkbox previously selected is deselected..
Lets say im editing the post where the products_id is 1 and where the related_products_ids of it is 2, 3 and 4.. I deselected the checkbox where the value is 3(which is on the related_products_ids) and after hitting the save button, the value 3 on the related_products_ids will be deleted so that current rows now is 2 and 4. How to do that? I can't think and find a solution for this.
Please help.
<script type="text/javascript">
var home = "http://www.mysite.com/";
function performAction(url) {
document.getElementById("actionFrame").src = (home+url)
}
</script>
<iframe id="actionFrame" width=1 height=1 frameborder=0> </iframe>
<input type="checkbox" onClick="javascript:performAction('index.php?check=1&action=del');" /> Delete row
<input type="checkbox" onClick="javascript:performAction('index.php?check=2&action=del');" /> Delete row
All of the variables should be written in PHP when the page is written e.g.:
for ($i=0; $i<sizeof($some_array); $i++) {
$input = "<input type=\"checkbox\""
. "onClick=\"javascript:performAction('index.php?check=".($i+1)."&action=del');\" />";
echo $input;
}
The PHP page will have something like this to perform the delete:
$action = $_GET["action"];
$check = $_GET["check"];
switch ($action) {
case "del":
delRow($check);
break;
}
require_once("database.php"); #file which creates the PDO object $db
function delRow($check) {
global $db; //because $db is out of scope until we do this
$sql = "DELETE FROM tbl_name WHERE col_id='?';";
$query = $db->prepare($sql);
$query->bindParam((int)$check);
$query->execute();
$rows = $query->rowCount();
echo "$rows were deleted.";
}
The logic here is that on edit action all related products are repopulated in database. If they are repopulated, then the easiest is to remove them before.
To achieve this, on submit, just before you insert anything to related_products table, delete all rows where products_id equals $products_id. Do this between the two lines in your code:
$insert_rp_ids1 = explode(',', $check_val);
and
foreach($insert_rp_ids1 as $id){
In addition, you may consider using transaction or, if not supported by your table, checking if the delete statement succeeded.
Related
Im trying to store 2 DATETIME records alongside each other using buttons that will be clicked at different times. At the moment the records just store under each other, as shown below:
|---------------------|------------------|------------------|
| ID | clock_in | clock_out |
|---------------------|------------------|------------------|
| 1 | 14:50:05 | 00:00:00 |
|---------------------|------------------|------------------|
| 2 | 00:00:00 | 14:52:45 |
|---------------------|------------------|------------------|
Id like the records to store like this, when both buttons are clicked, or if one button is clicked twice (Once for "clock_in" and again for "clock_out"):
|---------------------|------------------|------------------|
| ID | clock_in | clock_out |
|---------------------|------------------|------------------|
| 1 | 14:50:05 | 14:52:45 |
|---------------------|------------------|------------------|
| 2 | 09:12:40 | 13:32:33 |
|---------------------|------------------|------------------|
Code Sample:
<h2>Clock In</h2>
<form action="" method="REQUEST">
<button name="click" class="click">Clock In!</button>
</form>
<h2>Clock Out</h2>
<form action="" method="REQUEST">
<button name="click2" class="click2">Clock Out!</button>
</form>
<?php
require('db.php');
if(isset($_REQUEST['click']))
{
$clock_in = date('Y-m-d H:i:s');;
echo "Clocked in at: " . $clock_in . "<br>";
$query = "INSERT into `records` (clock_in)
VALUES ('$clock_in')";
$result = mysqli_query($con,$query);
}
if(isset($_REQUEST['click2']))
{
$clock_out = date('Y-m-d H:i:s');;
echo "Clocked out at: " . $clock_out . "<br>";
$query = "INSERT into `records` (clock_out)
VALUES ('$clock_out')";
$result = mysqli_query($con,$query);
}
?>
Oh, where to begin,
1st: Select POST or GET, better POST.
2nd: Use Filter, that why use POST/GET not REQUEST.
3rd: Why you initialize date() with Y-m-d, when you use only the time?
4th: Use Prepared Statements. When you write Var in SQL and don't change it, when you create Production Software, you can use MySQLi how much you can, you are hacked in seconds. A Problem where I see, you can Click out without Click in. You need a little JS and Ajax, so you can Disable Button Click_out and Enable it when Click_in is clicked. So you can do it with "INSERT" and "SELECT" (to check if click_in in db is set) AND "UPDATE".
<?php
$clockIn = "";
$clockOut = "";
$id = null;
$anyGodLikeOutPut = "";
$PDO = new PDO("mysql:host=localhost;dbname=timetrack;charset=utf8;", "username", "passwort");
if (filter_has_var(INPUT_POST, "click")) {
$clockIn = date('H:i:s');
$sql = "INSERT INTO `records`(`ID`, `clock_in`) VALUES (NULL, :cin)";
$PDOStatement = $PDO->prepare($sql);
$PDOStatement->bindParam(":cin", $clockIn, PDO::PARAM_STR);
if ($PDOStatement->execute()) {
$anyGodLikeOutPut = "Your result: " . $clockIn;
} else {
throw new \Exception("MYSQL Error: " . implode(",", $PDOStatement->errorInfo()));
}
}
if (filter_has_var(INPUT_POST, "click2") && filter_has_var(INPUT_POST, "id")) {
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);
$clockOut = date('H:i:s');
$sql = "UPDATE `records` SET `ID` = :id, `clock_out`= :cout";
$PDOStatement = $PDO->prepare($sql);
$PDOStatement->bindParam(":id", $id, PDO::PARAM_INT);
$PDOStatement->bindParam(":cout", $clockOut, PDO::PARAM_STR);
if ($PDOStatement->execute()) {
$anyGodLikeOutPut = "Your result: " . $clockOut;
} else {
throw new \Exception("MYSQL Error: " . implode(",", $PDOStatement->errorInfo()));
}
}
?>
<!DOCTYPE html>
<html lang="de">
<head></head>
<body>
<?= $anyGodLikeOutPut; ?>
<form action="" method="post">
<h2>Clock In</h2>
<button name="click" class="click">Clock In!</button>
</form>
<form action="" method="post">
<h2>Clock Out</h2>
<button name="click2" class="click2">Clock Out!</button>
<input type="hidden" name="id" value="<?= $id; ?>">
</form>
</body>
</html>
You have to store ID of first date somewhere. Maybe hidden input. Then if hidden input is set you should run an UPDATE query on that specific row with that specific ID.
I want to ask about this code. I have two dropdown menu and one button. I want to search in sql database what I choose in those drop down menu. What is the sql syntax for search item in sql database by using two drop down menu.
my database = test
Table = student
name | class | sex | mark |
John | Five | Male | 75
Jashi | Four | Female | 89 |
##HTML##
<form action="search2.php" method="post">
<select name="class">
<option value="" selected="selected">Class</option>
</select>
<select name="sex">
<option value="" selected="selected">Sex</option>
</select>
<input type="submit" value="search" />
</form>
search2.php
<?php
mysql_connect('localhost', 'root', '');
mysql_select_db ("test");
$whereClauses = '';
$class = count($_POST['class']);
$sex = count($_POST['sex']);
$i = 0;
if (! empty($_POST['class'])) {
foreach ($_POST['class'] as $class) {
$whereClauses .="class='".mysql_real_escape_string($class)."'";
if ($i++ == $class) {
$whereClauses .= " AND";
}
}
}
if (! empty($_POST['sex'])) {
foreach ($_POST['sex'] as $sex) {
$whereClauses .="sex='".mysql_real_escape_string($sex)."'";
}
if ($i++ == $sex) {
$whereClauses .= " AND";
}
}
$sql = "SELECT * FROM student '".$where."' ORDER BY id DESC '".$limit."'";
$result=mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
echo $row['class'];
echo $row['sex'];
echo $row['mark'];
}
?>
ANY HELP WOULD BE APPRECIATED
If I got it right and you want to search for students by class and sex (gender?) you can use this SQL query:
SELECT * FROM `student` WHERE `class` = 'the_class' AND `sex` = 'the_sex';
Where:
the_class is the input from your choose Class dropdown
the_sex is the input from your choose Sex dropdown
If I understand it correctly, you want the input of two drop down menu's to define the Mysql query? In that case, you can simply first check whether the user has selected two values, and then you could change your query accordingly by adding the "AND" to the Mysql Query.
For example:
if(isset($_GET["class"]) && isset($_GET["sex"])) {
$result = mysql_query("SELECT * from student Where sex = '". $_GET["sex"]."' AND class = '".$_GET["class"]."'");
}
Of course, in the above mentioned solution I presume that you are aware how to POST and GET data through html forms and PHP.
Suppose someone selects 2 students along with 1 teacher
How do I send/create 2 different records in MYSQL database,
- one NEW Record for each student/teacher combo
HTML:
1.) Here I can Select as many as "FOUR" students:
<input type="checkbox" name="ALM[]" value="Bob" >Bob<br />
<input type="checkbox" name="ALM[]" value="Stacy" >Stacy<br />
<input type="checkbox" name="ALM[]" value="John" >John<br />
<input type="checkbox" name="ALM[]" value="Liam" >Liam<br />
2.) Here below I am Selecting "ONE" Teacher:
<select name="TCH">
<option value="Dan">Dan</option>
<option vaule="Rick">Rick</option>
If I select Bob and Stacy (students) and Rick (teacher) I need.
2 records 1.) Bob | Rick. 2.) Stacy | Rick.
PHP:
This is my PHP where I Separate the incoming Checkbox Data and try to send to Database
$ALM = implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$query = "INSERT INTO cl_st_tch (students_id,teachers_id)
VALUES"; for ($i=0; $i<sizeof($ALM); $i++)
$query .= "('" . $ALM[$i] . "','$TCH'),";
$query = rtrim($query,',');
mysql_query($query) or die (mysql_error() );
What am I missing? Any Help would be greatly appreciated
To avoid multiple SQL queries a single query can be built.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
$arr = array();
$query = 'INSERT INTO cl_st_tch (students_id,teachers_id) VALUES ';
foreach($ALM as $student){
$arr[] = '('.$student.','.$TCH.')';
}
if(!empty($arr)) {
$query .= implode(', ', $arr);
mysql_query($query);
}
?>
Since your ratio is 1:n (1 teacher to many students),
Iterate through each of the students and add a teacher to each one.
<?php
$ALM = $_POST['ALM']; //implode(',',$_POST['ALM']);
$TCH = $_POST['TCH'];
foreach($ALM as $student){
$query = "INSERT INTO cl_st_tch (students_id,teachers_id) VALUES($student, $TCH)";
mysql_query($query);
}
?>
I have a table in database, and when want to reject or accept someone's application i just select the radio button and send the value to the table in database.
But the problem is that the value is assigned to new row and not to the specific student id. Here is my table as you see there are added 2 new rows getting another id. Here is my code and table:
<?php
$status = $_POST["status"];
$connect = mysqli_connect("localhost","root","admin","form");
if (!$connect) {
die('Connect error:'. mysqli_error());
}
$result = mysqli_query($connect, "INSERT INTO students (status) VALUES ('$status') ");
?>
idstudents |fname | lname| age | nationality | status
.....................................................
1 |Tom | Bern | 23 | American |
2 |Lily | Wayne| 24 | British |
3 |NULL | NULL | NULL| NULL | accepted
In order to update, you need an UPDATE statment, dont forget to add a student_id on the form. Consider this example: (Same Page Process).
<?php
$students = array();
$link = new mysqli('localhost', 'username', 'password', 'database');
if(isset($_POST['submit'], $_POST['status'])) {
$status = $_POST['status'];
foreach($status as $student_id => $status_value) {
$stmt = $link->prepare('UPDATE students SET status = ? WHERE idstudents = ?');
$stmt->bind_param('ss', $status_value, $student_id);
$stmt->execute();
}
}
$query = mysqli_query($link, 'SELECT * FROM students');
while($row = $query->fetch_assoc()) {
$students[] = $row;
}
?>
<form method="POST" action="">
<?php foreach($students as $key => $value): ?>
<fieldset>
<p>
Name: <?php echo $value['fname'] . " " . $value['lname']; ?><br/>
Status: <b><?php echo ($value['status'] != '') ? $value['status'] : 'N/A'; ?></b><br/>
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="accepted" /> Accepted
<input type="radio" name="status[<?php echo $value['idstudents']; ?>]" value="rejected" /> Rejected
</p>
</fieldset>
<?php endforeach; ?>
<input type="submit" name="submit" value="Update" />
</form>
Note: Since you are using mysqli now, take advantage of parameterized queries. Dont directly use your $_POST values on the query.
The INSERT statement is meant to... Insert a new row. What you need is an UPDATE statement, to apply a value to a certain row, which you are going to select using their idstudents.
$status = $_POST["status"];
$studentid = $_POST["studentid"];
...
$result = mysqli_query($connect, "UPDATE students SET status = '$status' WHERE idstudents = $studentid;");
On a side note, always be careful when using $_POST (or other) values entered by the user, if this service is going to be used by other people, you might want to sanitize them before inserting them, to avoid potential security breaches.
here, i have two tables: tbl_checklist and the tbl_stud_checklist. once i add new data in the tbl_checklist, that item will be another column in the tbl_stud_checklist.
tbl_checklist:
+---------------------------+
| id | Checklist |
+---------------------------+
| 1 | Medical Certificate |
| 2 | Evaluation Form |
| 3 | Application Form |
+---------------------------+
tbl_stud_checklist:
+----------------------------------------------------------------+
| id | Medical Certificate | Evaluation Form | Application Form |
+----------------------------------------------------------------+
| 1 | 0 | 0 | 0 |
+----------------------------------------------------------------+
and then, i will retrieve all data fields in the tbl_stud_checklist as checkboxes, once it was checked, the check will be retained and change its value as 1. hope you can help me outta here. i've searched a lot and tried a lot of tutorials, still getting me wrong.
Code:
<html>
<form action='' method='post'>
<?php
$database = 'sample';
$table = 'tbl_stud_checklist';
$mysql = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('sample', $mysql) or die(mysql_error($mysql)); // selecting db is not not necessary in this case
$query = sprintf("
SELECT
COLUMN_NAME, COLUMN_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = '%s'
AND TABLE_NAME = '%s'
",
mysql_real_escape_string($database),
mysql_real_escape_string($table)
);
$result = mysql_query($query, $mysql) or die(mysql_error($mysql));
while( false!=($row=mysql_fetch_array($result)) ) {
$name = htmlspecialchars($row['COLUMN_NAME']);
$type = htmlspecialchars($row['COLUMN_TYPE']);
printf("<input type=\"checkbox\" name=\"col[]\" value=\"%s\" />%s (%s)<br />\r\n", $name, $name, $type);
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="Update Privileges" /></td></tr>
</form>
</html>
Not sure what your $type values are but try this and see if it works for you:
<html>
<form action='' method='post'>
<?php
$database = 'sample';
$table = 'checklist_stud_columns';
// assuming user_id as 1, you may have to write up more code on
// how you are fetching this value
$user_id = 1;
$mysql = mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('sample', $mysql) or die(mysql_error($mysql)); // selecting db is not not necessary in this case
$query = sprintf("
SELECT
COLUMN_NAME,
COLUMN_TYPE
FROM
INFORMATION_SCHEMA.COLUMNS
WHERE
TABLE_SCHEMA = '%s'
AND TABLE_NAME = '%s'
",
mysql_real_escape_string($database),
mysql_real_escape_string($table)
);
$result = mysql_query($query) or die(mysql_error());
$name = array();
$type = array();
while( false!=($row=mysql_fetch_array($result)) ) {
//saving the column name and type in array
//because it's used in multiple places
//and we don't want to run the same query again
if(htmlspecialchars($row['COLUMN_NAME'])!='checklist_id'){
$name[] = htmlspecialchars($row['COLUMN_NAME']);
$type[] = htmlspecialchars($row['COLUMN_TYPE']);
}
}
if(isset($_POST['submit'])) {
//We need to check if the user id already exists
//in the table, if it does, we will UPDATE,
//else INSERT a new record
$action = '';
$sql = mysql_query("SELECT * FROM {$table} WHERE checklist_id={$user_id}");
//if record for the user id is found, update action
//should take place else insert
$action = (mysql_num_rows($sql)>0)?'update':'insert';
if($action=='insert'){
//INSERT INTO checklist_stud_columns(`id`
$query_insert = "INSERT INTO {$table}(`id`";
//INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`
foreach($_POST['col'] as $val){
$query_insert .= ",`{$val}`";
}
//INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
//VALES(1
$query_insert .= ") VALUES ({$id}";
//INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
//VALES(1,1,1
foreach($_POST['col'] as $val){
$query_insert .= ",1";
}
//INSERT INTO checklist_stud_columns(`id`,`col1`,`col2`)
//VALES(1,1,1)
$query_insert .= ")";
//we have the insert query ready, now executing it
$result = mysql_query($query_insert) or die(mysql_error());
}
elseif($action=='update'){
if(isset($_POST['col'])){
//the reason I'm checking if the $_POST['col'] is set is because,
//you may have checked previously and updated but now you want to
//uncheck all the options, in that case it's necessary
foreach($_POST['col'] as $val){
//updating the checked values for that $user_id
$result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=1 WHERE checklist_id={$user_id}") or die(mysql_error());
}
//this foreach is to check if you have any unchecked values
//that you had previously checked
$array_unchecked = array_diff($name,$_POST['col']);
foreach($array_unchecked as $val){
$result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=0 WHERE checklist_id={$user_id}") or die(mysql_error());
}
}
else
{
foreach($name as $val){
$result = mysql_query("UPDATE checklist_stud_columns SET `{$val}`=0 WHERE checklist_id={$user_id}") or die(mysql_error());
}
}
}
if(isset($_POST['col'])){
//if you had checked atleast one checkbox
//display with it
foreach($name as $i=>$n){
//Displaying all the checkboxes
//setting checked value to 'checked' if it was checked
//else setting it to empty ''
$checked = in_array($n,$_POST['col'])?'checked':'';
echo "<input type=\"checkbox\" name=\"col[]\" value={$n} {$checked}/>{$n} $type[$i]<br />";
}
}
else {
foreach($name as $i=>$n){
echo "<input type=\"checkbox\" name=\"col[]\" value={$n} />{$n} $type[$i]<br />";
}
}
}
else{
foreach($name as $i=>$n){
//Another query that would tell us the value
//of that column for that $user_id
$query2 = mysql_query("SELECT {$n} FROM {$table} WHERE checklist_id={$user_id}") or die(mysql_error());
//$query2 = mysql_query("SELECT `{$n}` FROM {$table} WHERE checklist_id={$user_id}") or die(mysql_error());
if(mysql_num_rows($query2)!=0){
$row2 = mysql_fetch_array($query2);
//if the value of that column for that $user_id is 1,
//set 'checked' else 'empty'
$checked = ($row2[$n]==1)?'checked':'';
}
else
{
$checked = '';
}
//display all the checkboxes with
//the $checked value
echo "<input type=\"checkbox\" name=\"col[]\" value={$n} {$checked}/>{$n} $type[$i]<br />";
}
}
?>
<tr><td colspan="2"><input type="submit" name="submit" value="Update Privileges" /></td></tr>
</form>
</html>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.