Prepared statement array explode - php

I am a beginner and I am trying to use prepared statement for edit page/ form,but i dont know how use to explode with prepared statement.I want to fetch data in array data in avery input.
For this <input type="text" name="adimpdate[]" id="adimpdate[]" value="<?php echo $row568->adimpdate; ?>" placeholder="enter">
<?php
$id= $_GET['id'];
$sql011 = $mysqli->prepare("SELECT * FROM detail WHERE id = ? ");
$sql011->bind_param("i",$id);
$sql011->execute();
$res658=$sql011->get_result();
?>
<?php
while($row658=$res658->fetch_object()){
?>
<table>
<tr >
<td id="imp" class="wrap">
<ul class="my_box">
<input type="text" name="adimpdate[]" id="adimpdate[]" value="<?php echo $row568->adimpdate; ?>" placeholder="enter" required>
<button id="impbtn" type="button" name="add" onclick="add_more()">Add</button>
</ul>
<input type="hidden" id="box_count" value="1">
</table>
<input id="uplbtn" type="submit" name="upload_all" value="UPLOAD">
</form>
</div>
</div>
</div>
I used Jquery to add more input and used implode to save data in database
<script>
/**(1)*****Important Dates******** */
function add_more(){
var box_count=jQuery("#box_count").val();
box_count++;
jQuery("#box_count").val(box_count);
jQuery(".wrap").append('<ul class="my_box" id="box_loop_'+box_count+'"><input type="text" name="adimpdate[]" id="adimpdate[]" placeholder="example- Application Begin : 22/01/2021"><button class="remove_field" type="button" onclick=remove_more("'+box_count+'")>Remove</button></ul>');
}
function remove_more(box_count){
jQuery("#box_loop_"+box_count).remove();
var box_count=jQuery("#box_count").val();
box_count--;
jQuery("#box_count").val(box_count);
}
</script>
<?php
}
?>

Prepared statement placeholders work somehow like php variable interpolation so to it does not replace any SQL.
You still have to use SQL IN() function to query by multiple values or define a single prepared statement to find by id and execute it for every entry in the array.
$ids = [1, 2, 3];
$sql011 = $mysqli->prepare("SELECT * FROM detail WHERE id = ? ");
foreach ($ids as $id) {
$sql011->bind_param("i",$id);
$sql011->execute();
$res658=$sql011->get_result();
}

Related

How can i get multiple value from POST variable using same name

When user inputs text in 'ctext' field and press accept, I want to fill the value=" " field with user input, i achieved this but it fills all the value fields of same name in the page, how can i achieve it for different value of different ctext input? Anyone please give me solution with example, Many thanks
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
$i=0;
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here" value="<?php $ctext = false; if(isset($_POST['ctext'])){ $ctext = $_POST['ctext']; } echo $ctext[$i]; ?>"></input>
<input type="hidden" name="id" value="<?php $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
$i++;
endwhile;
endif;
endif;
?>
I hope I understand what you want. You want to access the ctext for each individual $pen when printing the corresponding form.
You just need to name your <input> with a unique name and then access that value when printing. A possible solution is this:
<input type="text" name="ctext[<?php echo $pen['id']; ?>]" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } echo $ctext; ?>"></input>
What does it do?
name="ctext[<?php echo $pen['id']; ?>]" ensures a unique name for each $pen. For a $pen with id 1 this will result in name="ctext[1]".
if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } uses $pen['id'] to look up the corresponding value in $_POST['ctext'].
By the way, when outputting user input you should always escape it, e.g. with htmlspecialchars. This will look like this: echo htmlspecialchars($ctext); That way malicious input like "><script>alert('Hello!')</script> won't execute the javascript.
Update: as requested a solution using session to store data:
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
session_start();
if (isset($_POST['ctext'])) {
$_SESSION['ctext'][$_POST['id']] = $_POST['ctext'];
}
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_SESSION['ctext'][$pen['id']])){ $ctext = $_SESSION['ctext'][$pen['id']]; } echo htmlspecialchars($ctext); ?>"></input>
<input type="hidden" name="id" value="<?php echo $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
endwhile;
endif;
endif;
Note: I removed the now unnecessary counter $i. The session handling is mainly done before the while loop (start a session and store POST data). During output the values from the session are used. The name of the input is not an array anymore.
Change name of an input to an array.like this . When you submit the form you will get these values as an array. Give it a try
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here"></input>
I guess your code is misleading you, your form is in while loop so once any of the ctext input is filled your variable $_POST['ctext'] is set on server side and according to your code it sets all the value of ctext once accept is pressed.
You can have different names as a solution or an array indexing in input field name=“ctext[]” to avoid this.

php mysql adds forward slash on sql insert from array

I am inserting values checked from a form into a db, but the inserted value has a slash (/) at the end.
I am inserting into sql database from an array in a form with check boxes, I want to insert only the checked values.
The insert is okay for all the values but they appear with a slash at the end and I can't tell why it is like that.
Here is the form
<form role="form" method="POST" action="add_payroll.php">
<label>Employees</label><br>
<?php
// include "../includes/connect.php";
$cs = mysql_query("SELECT user_Idnum, salary, user_fname, user_lname,user_mname from tbl_user_details");
if($cs==true){
$count=mysql_num_rows($cs);
while($row=mysql_fetch_assoc($cs)){
extract($row);
echo '<input type="checkbox" name="detail_Id[]" value='.$user_Idnum.'/>'.$user_fname." ".$user_mname." ".$user_lname.'<br>';
}
}
?>
<label>Description</label>
<textarea class="form-control" name="description"></textarea>
<label>Transaction Date</label>
<input size="16" type="text" readonly name="transaction_date"class="form_datetime form-control">
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn dark btn-outline">Cancel</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
And here is the php script
<?php
include "../functions/connect.php";
$ids = $_POST['detail_Id'];
$desc = $_POST['description'];
$time = $_POST['transaction_date'];
foreach ($ids as $va) {
$run1= mysql_query("insert into tbl_payroll(detail_Id, description, transaction_date) values('$va', '$desc', '$time' )");
if($run1==true)
{
echo '<script language="javascript">';
echo 'alert("Successfully Added")';
echo '</script>';
echo '<meta http-equiv="refresh" content="0;url=report.php" />';
}
}
?>
Change
echo '<input type="checkbox" name="detail_Id[]" value='.$user_Idnum.'/>'.$user_fname." ".$user_mname." ".$user_lname.'<br>';
To
echo '<input type="checkbox" name="detail_Id[]" value="'.$user_Idnum.'"/>'.$user_fname." ".$user_mname." ".$user_lname.'<br>';
By having no quotes around the value attribute whatever is within that value will have a trailing slash concatenated to it's value.
You should probably not be writing out the javascript and meta-refresh in a loop either - the refresh will be triggered on the first iteration through the loop and subsequent statements will not be executed.
Also worth noting is the use of the now deprecated mysql functions - upgrade to either mysqli or PDO and use prepared statements to prevent SQL injection, something to which this code is vulnerable.
<?php
include "../functions/connect.php";
$ids = $_POST['detail_Id'];
try
if(substr($ids, -1) == '/') {
$ids = substr($ids, 0, -1);
}
or
$ids = rtrim($ids,"/");
..
$desc = $_POST['description'];
$time = $_POST['transaction_date'];
.......

Foreach update sql loop don't create loops

I have some strange problems with this codes:
The while loopp that contains a form inside
<?php
$sql = "SELECT * FROM sessions WHERE SES = '$SES' ORDER BY ID DESC";
$preorders = mysql_query($sql);
while ($pre = mysql_fetch_array($preorders)) { ?>
<tr>
<td class="center">
<form id="update" action="update" method="post">
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
</form></td>
</tr>
<?php } ?>
The submit button
<button type="submit" form="update">Update</button>
Process page
foreach ($_POST['ID'] as $key => $ID) {
$QTY = $_POST['QTY'][$key];
mysql_query("UPDATE sessions SET QTY= '$QTY' WHERE ID = '$ID' ");
}
THE ISSUE
That foreach update only the first item. Mostly, I need to update more than one item. Where is the problem?
Thank you so much!
There are multiple things going wrong with your code. First you use [] in this input's name:
<input type="number" name="QTY[]" value="<?=$pre[QTY]?>" min="1" max="100">
and this input as well:
<input type="hidden" name="ID[]" value="<?=$pre[ID]?>">
You probably want to place them inside <?php ... ?> tags.
Second. You only have one update button but multiple forms. Each form needs its own update button which needs to be included inside each <form> element.
Third. You're using the deprecated mysql functions. Change to mysqli or PDO.
Fourth. You should use Prepared Statements for your update query or else your code is susceptible to SQL Injection.

How to get value of button inside the foreach loop using post method

Objective: Get the value of buttons from $_POST method, inside foreach loop
$projects= 'Project1, Project2, Project3'//from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button.
Displaying all the project names on buttons.
<?php foreach ($projectNames as $val):?>
<form action="projectSelected.php" method="post" id="project">
<button style="float:left" class="btn-default" value=""> <?php echo $val;?> </button>
Problem statement: When user clicks on button 'Project1', program should be able to get the value of button with $_POST['projectSelected'].
Help would be appreciated.
Set the value in hidden, and then post the value
<form action="projectSelected.php" method="post" id="project">
<input type="hidden" value="<?php echo $val ?>">
<input type="submit">
1) change the name of your variables :
$Projects => $projects (PHP convention)
2) add a trim after your explode function
$projectNames = array_map('trim', $projectNames);
3) use input submit instead of buttons (similar question)
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
Complete example:
$projects = 'Project1, Project2, Project3'; //from mysql database
$projectNames = explode(',', $projects); // to separate the project names to display one by one on button
$projectNames = array_map('trim', $projectNames);
Loop:
<form action="projectSelected.php" method="POST" id="project">
<?php foreach ($projectNames as $val) : ?>
<input type="submit" style="float:left" class="btn-default" name="project" value="<?php echo $val ?>"/>
<?php endforeach ?>
</form>
DO this:
<button style="float:left" name = 'projectSelected' class="btn-default"
value=""> <?php echo $val;?> </button>
what ever you set the name of button will becomes the key of $_POST array

How to get ID from another file in php?

I'm going to make edit menu in my web. so I direct the page from product into edit page. What I'm confused is how to get the productID from product's page to use in edit page?
Here is my code in product
<?php $query= "SELECT * FROM game";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<div class="gameBox">
<div style="margin:5px;">
<?php echo "<image src=\"images/".$data['gameId'].".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <?php echo $data['gameName'];?></div>
<div class="myLabel">Developer</div><div>: <?php echo $data['gameDeveloper']; ?></div>
<div class="myLabel">Price</div><div>: $ <?php echo $data['gamePrice']; ?></div>
<br />
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
<input type="button" value="Delete"/>
</div>
</div>
<?php } ?>
and it's my code in edit page
<?php include("connect.php");
$id[0] = $_REQUEST['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" id="gameName" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" id="gameDeveloper" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" id="gamePrice" name="gamePrice"/></div>
<br/>
<div id="txtError">
<!--error message here-->
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php } ?>
When I try to access edit page, there's an error it said
"Undefined index:$id[0] = $_REQUEST['id'];"
in edit page.
Could anyone help me?
It looks like you're confusing two methods of passing data between pages, forms and query strings in <a href...>s.
Forms:
Data is in <input>-type elements (or friends) and inside a <form...> tag.
For example
<form action="handler.php">
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="submit">
</form>
Usually passed via POST and accessed in PHP via $_POST.
For example, the values in the text boxes referenced above would be accessed with something like:
<?php
echo $_POST['var1']; // First text box
echo $_POST['var2']; // Second text box
Links:
Passed as query strings in <a href...>, for example:
Click Me
Usually passed via GET and accessed in PHP via $_GET.
For example, the values in the query string provided above would be accessed with something like
<?php
echo $_GET['var1']; // "foo"
echo $_GET['var2']; // "bar"
So in this case it looks like you're hyperlinking an input button -- which is not the usual way to do things, but you would fix it by changing this:
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
To, this
<input type="button" value="Edit"/>
And then reference the variable in edit.php as $_GET['id'].
But since you know it's going to be an integer and nothing else, something like:
$id = (int)$_GET['id'];
Is good enough sanitation (at least for that variable).
Lastly, I notice you assign a variable to $id[0] but then reference $id. Assigning a variable to $id[0] is not the same as assigning it to $id, as $id is an array in the former and an integer in the latter. It seems to me that you can just drop the [0] w.r.t. $id in your edit.php
You can pass through the query string
<a href="edit.php?<?php $id=$data['gameId'];?>>
In this case your PHP code will get change to
$id[0] = $_SERVER['QUERY_STRING'];
Add the id as a parameter to your edit url:
<input type="button" value="Edit"/>
also at the top of your edit.php:
$id = $_REQUEST['id'];

Categories