php mysql adds forward slash on sql insert from array - php

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'];
.......

Related

Prepared statement array explode

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();
}

how can i use only one file instead of 4 php files that are basically the same?

i basically have a simple porgram to count how many times a click a specific button and then send it to mysql, but for each button i have diferent tables and separated files. I would like to know if there is any way to join the 4 files into only one, since it is repeating the same thing 4 times in diferent files.
Here is my code:
index.php
<!DOCTYPE html>
<html>
<head>
<title>Fct</title>
</head>
<body>
<form action="inserir.php" method="post">
<button name="A" type="submit" value="A">Senha A</button>
</form>
<form action="inserir2.php" method="post">
<button name="B" type="submit" value="B">Senha B</button>
</form>
<form action="inserir3.php" method="post">
<button name="C" type="submit" value="C">Senha C</button>
</form>
<form action="inserir4.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
</form>
</body>
</html>
and then the file to insert into mysql witch is inserir.php;
<?php
include 'bdados.php';
$A = $_POST['A'];
$query = "INSERT into `tipo1`(`senhaa`) VALUES ( '$A' )";
mysqli_query($dbconn, $query);
header("location: index.php");
?>
basically i have 4 "inserir.php" and i think i could shrink those 4 files in only one, i just dont know how.
All help is much apreciated :)
Add submit buttons with same name but different values.Retrieve the value by $_POST['name']
HTML
<form action="inserir.php" method="post">
<button name="val" type="submit" value="A">Senha A</button>
<button name="val" type="submit" value="B">Senha B</button>
<button name="val" type="submit" value="C">Senha C</button>
<button name="val" type="submit" value="D">Senha D</button>
</form>
PHP
<?php
include 'bdados.php';
$val = $_POST['val'];
$query = "INSERT into `tipo1`(`senhaa`) VALUES ( '$val' )";
mysqli_query($dbconn, $query);
header("location: index.php");
?>
I have a feeling your database schema could be improved, but without knowing the scope of your software, it's hard to make a recommendation. It looks like you want to change the table & the column-name based upon the value that is submitted. There are several different approaches that could help.
I'll change your query code to use a prepared statement (with PDO, as that's what I know)
PHP Switch
You'll have one file that handles all four of those submissions.
include 'bdados.php';
$key = array_keys($_POST)[0];
$value = $_POST[$key];
switch ($key){
case 'A':
$column = 'senhaa';
$table = 'tipo1';
break;
case 'B':
$column = 'senhab';
$table = 'tipo2';
break;
case ...
}
//The table name is hard-coded, so that part is not vulnerable to SQL injection
$query = "INSERT into `{$tableName}`(`senhaa`) VALUES ( :newValue )";
$bind = [':newValue'=>$value];
$pdo = new PDO(...);
$statement = $pdo->prepare($query);
$statement->execute($bind);//pass the ':newValue' to be bound
//Without binding, somebody could submit: `'');DELETE FROM senhaa WHERE (TRUE`
// This would close your INSERT statement with an empty value & delete everything from your table
// print_r($statement->errorInfo()); //for debugging if it doesn't work
header("location: index.php");
PHP Array
This will be much like above, but we'll replace the switch step with an array like:
$info = [
"A"=>['table'=>'tipo1','column'=>'tipo2']
"B"=> ['table'=>'tipo2'...]
...
];
$table = $info[$key]['table'];
$column = $info[$key]['column'];
Hidden HTML Inputs
Another approach could be to send identifying information through hidden input fields. While you should NOT send a table name this way, you could send some kind of identifier & then use the array-method above to map identifier to table info.
<form action="inserir-todo.php" method="post">
<button name="D" type="submit" value="D">Senha D</button>
<input type="hidden" name="identifier" value="the-fourth-table" />
</form>
Then you'd do:
$key = $_POST['identifier'];
$table = $info[$key]['table'];
...

datetime edit php to mysql error

I already connected my sql to database, but my isset post does not work
<div class="container" style="margin-top:60px;margin-bottom:60px;">
<div class="form-group pull-right">
</div>
<div class="row">
<p> Set Start DateTime<p>
<input type="datetime-local" name="start"><br><br>
<button type="submit" class="btn btn-primary" name="submit1">SUBMIT</button>
<br><br>
<p> Set Deadline<p>
<input type="datetime-local" name="end"><br><br>
<button type="submit" class="btn btn-primary" name="submit2">SUBMIT</button>
<br><br>
</div>
</div>
<?php
if(isset($_POST['submit1'])){
$name = $_POST['start'];
$sql = "UPDATE tbdeadline SET
start = '$name'
WHERE id = '1'
";
if ($this->con->query($sql) === TRUE){
echo '<script>window.location.href="deadline.php"</script>';
}
else{
echo 'error';
}
}
?>
I want to update datetime in my "user" database whose table name is "start" and id = "1"
But my html is getting nowhere. It is not showing any error or anything else.
What am I doing wrong, how can I fix this?
I think value from is not send via $_POST. If I want to check if form is send I use
<input type="hidden" name="submit1" value="1" />
And check via
if (isset($_POST['submit1'])
Try it.
The sql code is vulnerable to SQL injection - or it would be if it were not within single quotes rather than double. Using single quotes means that any PHP variable within must be escaped - easier to use double quotes and the values of the variables will be OK.
<p> Set Start DateTime<p>
<input type='datetime-local' name='start'><br><br>
<button type='submit' class='btn btn-primary'>SUBMIT</button>
<br><br>
<p> Set Deadline<p>
<input type='datetime-local' name='end'><br><br>
<button type='submit' class='btn btn-primary'>SUBMIT</button>
<br><br>
</div>
</div>
<?php
if( isset( $_POST['start'],$_POST['end'] )){
$name = $_POST['start'];
$end = $_POST['end'];
/* This is vulnerable to SQL injection !! */
/* use double quotes around sql or better mysqli/PDO and `prepared statements` */
$sql = "UPDATE tbdeadline SET start = '$name' WHERE id = '1'";
if( $this->con->query($sql) === TRUE ){
echo '<script>window.location.href='deadline.php'</script>';
} else{
echo 'error';
}
}
?>
You forgot to add the values for your Submit buttons.
You need to update your Submit buttons like below:
<button type="submit" class="btn btn-primary" name="submit1" value="start">SUBMIT</button>
<button type="submit" class="btn btn-primary" name="submit2" value="end">SUBMIT</button>
Also make sure your form method must be POST like below:
<form method="post">
If you still get isset error then you need to debug your $_POST to check whether form data is coming via form or not. Add below code before if condition to test:
print_r($_POST); die;
And use MySqli Prepared Statements for updating your query to make it more Secure.
Follow below link to learn more:
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

UPDATE inside a WHILE statement

So, I have a page with a bunch of workorders on it. Each workorder is a row in a single table, and gets put on the page with a while() statement.
I'm trying to update each row with a simple form that I put inside the while(), and an UPDATE/WHERE statement to actually add the information to the table.
Instead of adding it to the specific row, it adds it to Every row. The only thing I can think of is that my WHERE condition is wrong, but I can't seem to figure it out. Maybe it just needs fresh eyes, or maybe I'm heading in Completely the wrong direction.
Also, any specific instructions on security, a better way to do it, etc. would be very helpful. I'm learning PHP on the fly and could use a helping hand. :)
<?php
$query = "SELECT * FROM client_information";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$which_ad = $row['ID'];?>
<b>Name:</b> <? echo $row['billing_name']; ?> <br>
<b>Job Type:</b> <? echo $row['job_type']; ?> <br>
<b>Size:</b> <? echo $row['size']; ?> <br>
<b>Text:</b> <? echo $row['text']; ?> <br>
<b>Notes:</b> <? echo $notes; ?> <br>
<br><br>
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="submit" name="submit" value="Submit"></form>
<?
$email_message = htmlspecialchars ("{$_POST['email_message']}", ENT_QUOTES);
if (mysql_errno() != 0) {
die(mysql_error());
}
mysql_query(
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$which_ad'"
);
if (mysql_errno() != 0) {
die(mysql_error());
}
}
?>
You don't specify the id in your form:
<form action="small_update.php" method="POST">
<strong>Email Message:</strong><br>
<textarea rows="8" cols="60" name="email_message"></textarea>
<input type="hidden" name="id" value="<?php echo $which_ad; ?>">
<input type="submit" name="submit" value="Submit">
</form>
you need to also make sure you know what id was submitted:
"UPDATE client_information
SET email_message='$email_message'
WHERE ID='$_POST['id']'"
Of course, you're wide open to attacks like this as everyone else is saying. You need to look into mysqli or pdo to sanitize your input...
Ans also upon inspection you're evaluating your post data in the loop. Don't do that. Just do your evaluation before everything else is processed on the page...
<?php
if($_POST)
{
//run processing here
}
// do your fetch code here and display the forms...

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