Checkbox not getting right order - javascript

I have these checkboxes used for identifying (if checked) should email the respective client, it's supposed to be pre-checked.
But when it is pre-checked, and then when I unchecked one checkbox e.g multipayment_email[1], when submitted to PHP the one getting unset is the last index multipayment_email[4].
list_payments.php:
<form method="POST">
<?php while($row = mysqli_fetch_array($selectQuery) { ?>
<input type="text" name="multipayment_name[]" required/>
<input type="checkbox" name="multipayment_email[]" checked />
<?php } ?>
</form>
SUBMIT_payment.php:
$names = $_POST['multipayment_name'];
$emails = $_POST['multipayment_email'];
foreach ($names as $key => $name)
{
$email = isset($emails[$key]) ? 1:0;
$query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";
$response['message'] .= $query."<br/>";
}
die(json_encode($response));
So when I submit the form this is the output (given that I unchecked the 2nd index out of 5 check boxes):
"INSERT INTO payments() VALUES (NULL, '1 waw', 1)"
"INSERT INTO payments() VALUES (NULL, '2 wew', 1)"
"INSERT INTO payments() VALUES (NULL, '3 wiw', 1)"
"INSERT INTO payments() VALUES (NULL, '4 wow', 1)"
"INSERT INTO payments() VALUES (NULL, '5 wuw', 0)"
It should be
"INSERT INTO payments() VALUES (NULL, '2 wew', 0)"
any enlightenment?

Try this:
<form method="POST">
<?php $idx = 0; ?>
<?php while($row = mysqli_fetch_array($selectQuery)): ?>
<input type="text" name="rows[<?php echo $i; ?>][name]" required/>
<input type="checkbox" name="rows[<?php echo $i; ?>][email]" checked />
<?php ++$idx; ?>
<?php endwhile; ?>
</form>
And so if third checkbox is unchecked, you will obtain the $_POST data in this format:
array(
'rows' => array(
array(
'name' => 'the value of name 1',
'email' => 'on'
),
array(
'name' => 'the value of name 2',
'email' => 'on'
),
array(
'name' => 'the value of name 3'
)
)
)
Checkboxes that doesn't check will have the field unset and not being posted, and from there you can easily do an isset check to know if it's checked or not.
$rows = $_POST['rows'];
foreach ($rows as $row) {
$email = isset($row['email') ? 1 : 0;
$name = $row['name'];
$query = "INSERT INTO payments() VALUES (NULL, '$name', $email)";
$response['message'] .= $query."<br/>";
}
But DO WARNED that this code is susceptible to sql injection. Since this is out of the scope of this question let us not dive into that here :)

All Inputs need to have different names.
Now there are a faw Inputs with two names multipayment_name[] and multipayment_email[]

The last one is not being unchecked, this line of code is giving you the undesired result.
$email = isset($emails[$key]) ? 1:0;
When you uncheck the checkbox, it won't be submitted to the server. dump your submitted checkboxes array i think you will get it )

Related

Database generated dropdown giving more variables a value from the same database when selected

I hope the title wasn't too cryptic, and I am sure there will be other threads like this one but cannot seem to put my finger on the correct terminology.
I have a form that has 3 dropdowns. Let's call them 'sales consultant', sales email & sales team.
What I am looking to do is give a value to 'sales email' & 'sales team' when the sales consultant is chosen from the dropdown 'sales consultant'
The catch, I am using mysql to pull the data for each dropdown. See below:
<div id="sc">
Sales Consultant
<input class="" type="text" list="salesconsultant" name="salesconsultant" placeholder="Start typing consultants name" required />
<datalist id="salesconsultant">
<?php
$sql = "SELECT consultant, id FROM salesconsultants";
$result = $conn->query($sql);
if (!$result) die($conn->error);
if($result->num_rows > 0 ) {
while($row=$result->fetch_assoc()) {
echo "<option value=\"".$row["id"]."\">".$row["consultant </option>";
}
echo "</datalist>";
} else {
echo"record 0";
}
?>
</div>
The other rows I have in the database are 'salesemail', 'id', 'consultant' and 'teamid'.
So when sales consultant 1 is selected it will give the variable $salesemail the value of consultant 1's 'salesemail' and so on.
Is this possible?
Just change below line to :
echo '<option value="'.$row["id"].'".','."'.$row["salesemail"].'">'.$row["consultant"].'</option>';
In above code you are separating both value by , And you can get these values like this :
$result = $_POST['yourselectbox'];
$r1 = explode(',', $result);
echo "id: ". $r1[0]."<br />";
echo "email: ". $r1[1]."<br />";
Hope this will work!

Combine input box and select box to create a search bar

I have an input box that serves as a search box, and I populate a select box by querying a SQL database. For example, there are two organizations called "Dummy Organization" and "Dummy 2" in my db. So when the user starts typing "du", the select box fills with those two organizations. What I want to do is to combine these two fields: the input box (that acts as the search box) and the select box (which displays the results). My research shows that selectize.js can be useful, but since I'm new to js, I can't figure out how. Can someone please help me? My code is as below:
js that gets the data from the db:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output4){
$("#output4").html(output4);
}
</script>
The form:
<form action="newbrand.php" method="post" id="form">
<br>
Brand Name: <input type="text" name="bname" required /><br><br>
Search for an Organization: <input type="text" required name="search" onkeyup="searchq()" id="output"><br><br>
Selected Organization:
<select id="output4" name="taskOption"></select>
</form>
The search.php file
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<option>No results!</option>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<option value="<?php echo $orgid; ?>"><?php echo $orgname; ?></option>
<div><?php echo $subs; ?></div>
<?php
} // while
} // else
} // main if
?>

2 values for a single input box and storing the 2nd value in php

I am using two values for 1 input box, when user selects multiple boxes the values will be submitted to submit_checkbox.php. I want to save the 2nd value i.e value after "|" sign in the php form. How can I do it ? My code is as follows :-
<form name='checkbox' method="post" action="submit_checkbox.php">
<b><h3>Select option</h3></b>
<input type="hidden" name="qq1[]" value="null">
<input type="checkbox" name="qq1[]" value="ABC|DEF"> A<br>
<input type="checkbox" name="qq1[]" value="GHI|IJK"> B<br>
<input type="checkbox" name="qq1[]" value="LMN|PQR"> C<br>
<input type="submit" value="SUBMIT" >
</form>
And in "submit_checkbox.php" the code is as follows :-
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root1';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("my_db") or die(mysql_error());
list($value1,$value2)=explode('|',$_POST['qq1']);
$values=implode(',', $value2);
$sql = "INSERT INTO print_chk VALUES ('$values')";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
else
{
echo "Success";
}
?>
However, I am unable to put the 2nd value in the sql table "print_chk".
Your $_POST['qq1'] is an array, so you have to explode every element of it and then make the string from this. Try something like this, it works for me:
//Get the second part
function GetSecond($v) {
if ($v != 'null') {
$a = explode('|',$v);
return $a[1];
}
else {
return '';
}
}
//Since $_POST['qq1'] is an array, get the second part of each item
$v = array_map('GetSecond',$_POST['qq1']);
//Filter out the empty strings
$v = array_filter($v);
//Implode the list
$values = implode(',',$v);
//Insert to DB
$sql = 'INSERT INTO print_chk VALUES ("'.mysql_real_escape_string($values).'")';

Create session variables out of looped database values

I am attempting to create a variable from a database array when an HTML link is clicked. The goal is to redirect the user to a form populated using one piece of array data. In other words, the database will be queried and form populated according to which link is clicked (whatever the values of $row[1], $row[2], and $row[3] are).
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
If anyone can provide me with some incite as to how I could accomplish this I'd appreciate it greatly.
Please read more about sessions here
Then, to answer your question:
First you need to start the session, as simple as session_start(); on the top of your script.
Second you need to instantiate session variables with the DB values like this: $_SESSION['var'] = $value;.
Third, in the html file or whatever, where the form relies, just check for it:
if(isset($_SESSION['var'])) {
echo '<input type="text" value="'.$_SESSION['var'].'" />';
} else {
echo '<input type="text" value="" />';
}
and use the value if it is set.
L.E:
So... first thing's first... session_start(); without it, there is no point of having session.
Second, you create it like $_SESSION['some_name'] = $row[1] so that var will keep the value from $row[1]. I am presuming that it's the value you need. Do NOT do do it like $_SESSION['$row1'] because first of all this is incorrect, you will NOT have the value of row1 there. You need an unique name so that you can call it where you have the form.
The above code will become something like this:
<?php
session_start();
ini_set('display_errors',1); error_reporting(E_ALL);
$DATE = date('Y-m-d');
require_once 'IRCconfig.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if ($connection->connect_error) die($connection->connect_error);
$query = "SELECT * FROM CLIENT_CHECKIN1 WHERE DATE>='$DATE'";
$result = $connection->query($query);
if (!$result) die ("Database access failed: " . $connection->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
$_SESSION['first_row'] = $row[1];
$_SESSION['second_row'] = $row[2];
$_SESSION['third_row'] = $row[3];
echo <<<_END
<pre>
$row[1] $row[2] $row[3]
</pre>
_END;
}
?>
and, where you have the form and the <input type = "text" value = "" /> so where you need the value, just do it like this:
<input type = "text" value = "<?php echo (isset($_SESSION['first_row']) ? $_SESSION['first_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['second_row']) ? $_SESSION['second_row'] : ''); ?>" />
<input type = "text" value = "<?php echo (isset($_SESSION['third_row']) ? $_SESSION['third_row'] : ''); ?>" />
Hope this helps! :D

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources