PHP update SQL form - php

I wrote this using various helper guides online:
<?php // update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins ".
"SET is_private = $emp_salary ".
"WHERE id = $pinDetails->id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
<?php
}
?><!-- update -->
I'm trying to create an online form which I can return to to change posts from public to private simply by entering 1 for private or 0 for public as a moderation tool.
However, when I submit the form, (which works) every time I revisit the page it just says the echo statement 'post is now private'. I want to be able to see the form everytime, so I can re-use again and again when necessary.
What do I need to change in order to achieve this?

Remove else in last condition.
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins ".
"SET is_private = $emp_salary ".
"WHERE id = $pinDetails->id" ;
mysql_select_db('test_db');
$retval = mysql_query( $sql );
if(! $retval )
{
die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>

after:
echo "Post is now private<br><br>";
add this:
echo 'see form';
Your problem is that the form post variables are still being sent to the server so your if statement
if(isset($_POST['update']))
evaluates to true and the form doesnt' display.

Related

Dynamic insertion of data into database

I have tried out some code for dynamic insertion of data using array but the issue am facing is in a single row same data is been inserted and even if check box are left un-checked data value is inserted ignoring the checked value inside a "while-loop"..I am new to this array concept please help me out.
.php
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<div class="col-md-12">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
echo '
<tr>
<td align="left">' . $row['via'] . '<input type="hidden" name="type[]" value="' . $row['via'] . '"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>';
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
DB.php
<?php
session_start();
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(isset($_POST["submit"]) && isset($_POST["type"])){
//receiving post parameters
$types = $_POST["type"];
if(sizeof($types) > 0 ){
foreach($types as $type){
// create a new user profile
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$type."','".$type."','".$type."','".$type."', NOW())";
if(mysqli_query($con,$sql)){
header('Location: macro_ppl.php');
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}
}
}
?>
First of all checkbox values will not be present in the post if they are not set.
Second of all you add many results cause you call insert sql in the loop.
You can use:
var_dump($_POST['type']);
so you will see how the structure actually look like.
There are many ways to make this work one could be:
//setting the variables first
$ppl = 0;
$macro = 0;
$micro = 0;
$nano = 0;
//then run the loop to set them
foreach($types as $type){
if(in_array($type,['ppl','macro','micro','nano'])) //just to be sure nobody pass something else so we will not override other variables
$$type = 1;
}
//then write the query
$sql = "INSERT INTO ppl_tbl (vault_no, via, gname, ppl, macro, micro, nano, created_at) VALUES ('".$_SESSION['via']."', '".$_SESSION['vault_no']."', '".$_SESSION['gname']."', '".$ppl."','".$macro."','".$micro."','".$nano."', NOW())";
You are doing it wrong, just submit a form with data array
Form
<form id="form" name ="form" method = "POST" action="someForm.php">
<tr>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
</form>
someForm.php
if (isset($_POST['type'])) {
foreach ($_POST['type'] as $myType) {
echo $myType
}
}
Your Form
<form id="form" name ="form" method = "POST" action="move_ppl.php" class="wizard-big" autocomplete = "off" enctype="multipart/form-data">
<?php
$con = mysqli_connect("localhost","***","***","***");
$query = ("SELECT * FROM profile");
$result = mysqli_query($con, $query);
while ($row = $result->fetch_assoc())
{
?>
<tr>
<td align="left"><?php echo $row['via'] ?><input type="hidden" name="type[]" value="<?php echo $row['via'] ?>"></td>
<td align="left"> <input type="checkbox" name="type[]" value="macro"/> Macro </td>
<td align="left"> <input type="checkbox" name="type[]" value="micro"/> Micro </td>
<td align="left"> <input type="checkbox" name="type[]" value="nano"/> Nano </td>
</tr>
<?php
}
?>
<input style="width: 100%;" type="submit" name = "submit" id = "submit" value="Move" class="btn btn-info"><br><br>
</form>
In PHP file
if (isset($_POST['submit'])) {
if(isset($_POST['type'])) {
foreach ($_POST['type'] as $value) {
echo $value;
/*add this in the query, this will return the value of checkbox which are checked*/
}
}
}

Flexibility within 'Print/Echo'

I made this code:
<?php if($this->session->userdata('login_user_id'));
$a = $this->session->userdata('login_user_id');
$b = mysql_query("SELECT * FROM user WHERE id='$a' AND specialrank='1'")
or die(mysql_error());
while($c = mysql_fetch_array( $b ))
{
Print $c['username'];
}
?>
basically it creates a session for the logged in user.
I want to be able to show more in the print section though, some advanced php code and html form. Is there a way I can do this by reworking the code? It seems I'm limited with regards to which characters I can use within the print statement.
Basically, I want to display a form to specific users and not others.
I have tried closing the <?php ?> tags after every line to see if that works but it throws up errors of unexpected and expected's etc.
EDIT:
this is the segment of code I want to show:
<?php // update
if(isset($_POST['update']))
{
$id = $_POST['id'];
$emp_salary = $_POST['emp_salary'];
$sql = "UPDATE pins SET is_private = $emp_salary WHERE id = $pinDetails->id";
mysql_select_db('test_db');$retval = mysql_query( $sql );if(! $retval )
{ die('Could not change: ' . mysql_error());
}
echo "Post is now private<br><br>";
}
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Private
<input name="emp_salary" type="text" id="emp_salary" value="1">
<input name="id" type="hidden" id="id">
<input name="update" type="submit" id="update" value="Change">
</td>
</tr>
</table>
</form>
As you can see, simply putting that within the print throws up so many errors.

Records not getting inserted in ascending order

I'm having a strange problem. I have a HTML page with PHP code which inserts data to a MySQL database. The data gets saved to the DB without any errors but in an incorrect order.
Here's a screenshot. The table on the right side displays the existing records. The first 2 records are shown correctly.
But when I save more records, it displays like this.
Even in the MySQL table, the records are inserted that way.
I'm not sure where exactly the problem is so I've shown the whole code for the page below. I've commented what each code block does. Please comment if you need me to clarify something.
The Location ID is an auto-generated code.
<html>
<head>
<script language="javascript">
function SelectAll(source)
{ //The code for the 'Select All' checkbox
checkboxes = document.getElementsByTagName("input");
for(var i in checkboxes)
{
if(checkboxes[i].type == 'checkbox')
{
checkboxes[i].checked = source.checked;
}
}
}
</script>
</head>
<body>
<?php
//Database connection initialization
require_once("db_handler.php");
$conn = iniCon();
$db = selectDB($conn);
/* Generating the new Location ID */
$query = "SELECT LID FROM locations ORDER BY LID DESC LIMIT 1";
$result = mysql_query($query, $conn);
$row = mysql_fetch_array($result);
$last_id = $row['LID'];
$id_letter = substr($last_id, 0, 1);
$id_num = substr($last_id, 1) + 1;
$id_num = str_pad($id_num, 3, "0", STR_PAD_LEFT);
//$id_num = sprintf("%03d", $id_num);
$new_id = $id_letter . $id_num;
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations";
$result = mysql_query($query, $conn);
$count = mysql_num_rows($result);
?>
<! The table which displays the existing records >
<div id="display">
<b>Locations</b><br/><br/>
<form name="displayLocs" action="<?php echo $PHP_SELF; ?>" method="post" >
<table border="1">
<tr>
<th>Location ID</th>
<th>Code</th>
<th>Location</th>
<th><i>Delete</i></th>
</tr>
<?php
while($row = mysql_fetch_array($result))
{
?>
<tr>
<td align="center"><? echo $row["LID"]; ?></td>
<td align="center"><? echo $row["Code"]; ?></td>
<td><? echo $row["Location"]; ?></td>
<td align="center"><input type="checkbox" name="checkbox[]" value="<? echo $row["LID"]; ?>" /></td>
</tr>
<?php
}
?>
</table>
<br/>
<div id="buttons2">
<input type="checkbox" onclick="SelectAll(this)" />Select All <input type="reset" value="Clear" /> <input type="submit" value="Delete" name="deletebtn" />
</div>
</form>
</div>
<! New record saving area >
<b id="loc_caption_1">Enter a new location</b>
<div id="loca">
<form name="locForm" action="<?php echo $PHP_SELF; ?>" method="post" >
<table width="300" border="0">
<tr>
<td>Location ID</td>
<td><input type="text" name="lid" readonly="readonly" value="<?php echo $new_id; ?>" style="text-align:right" /></td>
</tr>
<tr>
<td>Code</td>
<td><input type="text" name="code" style="text-align:right" /></td>
</tr>
<tr>
<td>Location</td>
<td><input type="text" name="loc" style="text-align:right" /></td>
</tr>
</table>
</div>
<br/>
<div id="buttons">
<input type="reset" value="Clear" /> <input type="submit" value="Save" name="savebtn" />
</div>
</form>
<?php
//Saving record
if(isset($_POST["savebtn"]))
{
$id = $_POST["lid"];
$code = $_POST["code"];
$location = $_POST["loc"];
$query = "INSERT INTO locations(LID, Code, Location) VALUES('$id', '$code', '$location')";
$result = mysql_query($query, $conn);
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<br/><br/>";
echo "<strong>1 record added successfully!</strong>";
echo "<meta http-equiv=\"refresh\" content=\"3;URL=locations.php\">";
}
mysql_close($conn);
}
//Deleting selected records
if(isset($_POST["deletebtn"]))
{
for($i = 0; $i < $count; $i++)
{
$del_id = $_POST["checkbox"][$i];
$query = "DELETE FROM locations WHERE LID = '$del_id' ";
$result = mysql_query($query, $conn);
}
if (!$result)
{
die("Error " . mysql_error());
}
else
{
echo "<meta http-equiv=\"refresh\" content=\"0;URL=locations.php\">";
}
mysql_close($conn);
}
?>
</body>
</html>
Can anyone please tell me what is causing this and how to rectify it.
Thank you.
The records in the database are stored in the database in no particular order (well, there's some order to it, but it's up to the engine to determine it). If you want to get the results in a particular order, then you need to explicitly specify it when querying the data. In your case, make this change:
/* Displaying the exsisting locations */
$query = "SELECT * FROM locations ORDER BY lid";
$result = mysql_query($query, $conn);

Updating a table with PHP and MYSQL

<?php require("inc_connect.php"); ?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td align="left" valign="top">
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name">
<br />
ID:
<label for="select"></label>
<select name="id">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while($output = mysql_fetch_array($run)){
echo "<option value=\"{$output['id']}\">{$output['id']}</option>";}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td width="300" align="left" valign="top"><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
The above is the index page ...
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}'";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{mysql_error();}
?>
And this is the page that processes the form.
The problem is that the record won't update if i set the id={$_GET['id']}
and if I remove that part it updates all the rows.
So updating according to id ...
Thanks in Advance
FarrisFahad
Try changing your form action to
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
Also, doing an echo of $query might help debug your problem.
First, just be aware of SQL Injection - your code is wide open to it. See http://bobby-tables.com/
PHP Code
<?php
$connect = mysql_connect("localhost","root","");
$sel_database = mysql_select_db("test");
$name = mysql_real_escape_string( $_POST["name"] );
$id = (int) $_GET['id'];
$query = "UPDATE test SET name='{$name}' WHERE id = {$id}";
if($run = mysql_query($query)){
header("location: index.php");
exit;
}else{
# In production, don't show raw errors to users - log them to a file and
# present the user with a generic "There was a problem with the database"
# error. Or people can start sniffing for vulnerabilities in your site.
echo mysql_error();
}
?>
Page
<?php
require("inc_connect.php");
?>
<h1 align="center">Farris Website</h1>
<hr width="1000">
<p align="center">
<table align="center" width="1000" border="3" bordercolor="#0066FF" >
<tr>
<td><form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_GET['id']); ?>">
<p><strong>Enter Name:</strong>
<input type="text" name="name"><br />
<label for="select">ID:</label>
<select name="id" id="select">
<?php
$query = "SELECT * FROM test";
$run = mysql_query($query);
while( $r = mysql_fetch_array($run) ){
# I always use short, single character, variables when in loops.
# Saves alot of characters and potential confusion.
echo " <option value='{$r['id']}'>{$r['id']}</option>\n";
}
?>
</select>
</p>
<p>
<input type="submit" name="submit" value="Update!">
</p>
</form></td>
<td><?php include("inc_output.php"); ?></td>
</tr>
</table>
</p>
As you want to update that record which is selected from your dropdown. Moreover u have set your form method to POST. So you should try following:
<form name="update" method="post" action="ex_update.php?id=<?php echo urlencode($_POST['id']); ?>">

updating database with user edit post

I am trying to update my database with a post that a user has edited in a forum. The whole edit form is functioning except for: when they click edit, the form submits and goes to the main forum page, but the database and the post don't change.
My save edit code is this:
#data preparation for the query
$id=intval($_POST['id']);
$a_id=intval($_POST['a_id']);
$question_id=intval($_POST['question_id']);
foreach ($_POST as $key => $value)
$_POST[$key] =
mysql_real_escape_string($value);
$sql = "UPDATE $tbl_name SET
a_answer='$_POST[a_answer]' WHERE
a_id='$a_id' AND
question_id='$question_id'";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error()); }
mysql_close; header ("location:
main_forum.php");
?>
My code for the edit page is this:
#data preparation for the query
$id=intval($_GET['id']);
$a_id=intval($_GET['a_id']);
$question_id=intval($_GET['question_id']);
# selects title and description fields from database
$sql = "SELECT a_answer FROM $tbl_name WHERE a_id='$a_id' AND question_id='$question_id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
?>
And the HTML
<h3>Edit</h3>
<form action="save_edit.php" method="get" name="myForm" />
<center>
<table>
<tr>
<td valign="top">
<b>Answer</b>
</td>
<td>
<textarea cols="80%" rows="10" name="a_answer">
<?php echo htmlspecialchars($rows['a_answer']); ?>
</textarea>
</td>
</tr>
<tr>
<td colspan="3">
<input name="a_id" type="hidden" value="<? echo $rows['a_id']; ?>">
<input name="question_id" type="hidden" value="<? echo $rows['question_id']; ?>">
<input type="submit" name="Submit" value="edit post">
<?php mysql_close(); ?>
</input>
</input>
</input>
</td>
</tr>
</table>
</center>
You are mixing up get and post. In your form you use method="get" while you use $_POST in the processing page. Change your form to method="post":
<form action="save_edit.php"
method="post" name="myForm">
PS. You shouldn't close an opening tag with />.

Categories