POST variable is not being saved correctly - php

Im using method post to send a mutliple input text form, i draw information from the database to after re insert the information which is inside input text:
echo "<CENTER><TABLE BORDER='0'>";
echo "<FORM METHOD='POST'>";
$sele_players = "SELECT nombre FROM JUGADORES WHERE NOM_EQUIPO='Aston villa'";
$sele_players = mysql_query( $sele_players , $link );
while( $row = #mysql_fetch_assoc( $sele_players ) )
{
$row['nombre'] = addslashes( $row['nombre'] );
echo "<TR><TD ALIGN='CENTER'>".$row['nombre']."</TD>";
echo "<TD><INPUT TYPE='TEXT' NAME='{$row['nombre']}'></TD></TR>";
}
echo "<TR><TD COLSPAN='2' ALIGN='CENTER'><INPUT TYPE='submit' NAME='send2' VALUE='INSERTAR' style='width:200px; height:60px' ></TD></CENTER></TR>";
ok here i get the names of players from database, then i use them for insert inside input text as his name, to after pick with array $_POST:
if( !empty( $_POST['send2'] ) )
{
foreach($_POST as $jugador => $points)
{
$jugador = str_replace( "__" ,". ", $jugador );
$jugador = str_replace( "_" ," ", $jugador );
if( $points == "" )
{
$points = "NULL";
}
$inser_jornada = "INSERT INTO JORNADA VALUES( '{$_GET['jornada']}','{$_GET['equipo']}', '$jugador', '$points', now() );";
So there is no problem with most of names, excluding N'Zogbia name or apostrophe names which is shown in $_POST array as 'N', i have tried adding slashes before send it through from but doesnt work, so i dont know how to get the complete name in post array, thats the main problem.
THanks forwarded!!

There are many things to point out here. But instead of that, I will try my best to be helpful.
Add your database entries using mysql_real_escape_string($variableName) to enter the content to the database. It will automatically escape such quotes and make it a little SQL Injection proof.

As it was mentioned before, your code "screams" help. There are lot of things to point out, but back to your answer: I think your problem is in the following line:
$inser_jornada = "INSERT INTO JORNADA VALUES( '{$_GET['jornada']}','{$_GET['equipo']}', '$jugador', '$points', now() );";
Try this instead:
$inser_jornada = 'INSERT INTO JORNADA VALUES( "' . $_GET['jornada'] . '", "' . $_GET['equipo'] . '", "' . $jugador . '", "' . $points . '", now() );';
I would really, really recommend that you run mysqli_real_escape_string() to all your input.
Good luck!

Related

Inserting values from multiple checkboxes and textfields

I am a beginner in PHP.I am stuck with a problem. The idea is that I have to assign actors to a selected movie and add a role for each. I need to pick several values from the list and add a description for each via texfields. My code adds all the checked values to the database, but it makes a mess with the values from the textfields, the checked values don't match with the description. I would be really grateful for your help!
My code:
Form:
<?php
$sqlquery = "SELECT artistId, firstname, lastname from $artists order by 2";
$result = mysqli_query($connect, $sqlquery);
if($result) {
echo "<table class=\"addactor\">";
echo "<tr>
<td id=\"text\" colspan=\"2\"><h3>Assign an actor to the movie</h3></td>
</tr>";
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[]\"/></td>";
echo "</tr>";
}
echo "<tr><td align=\"right\"><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Add\"></td><td><input type=\"reset\" name=\"reset\" id=\"reset\" value=\"Reset\"></td></tr></table>;";
}
print '</table>';
The connection to the database is in another file, which is included here.
The second part:
if($_POST) {
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
$len = sizeof($checkbox);
for($i = 0; $i < $len; $i++) {
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $checkbox[$i] . "', '" . $_POST['moviecode'] . "', '" . $txt[$i] . "')";
mysqli_query($connect, $sqlqr);
}
$query = "INSERT INTO $movies(movieCode, title, dateOfIssue,category, description, image) VALUES ('" . $_POST['moviecode'] . "', '" . $_POST['title'] . "', '" . $_POST['dateofissue'] . "','" . $_POST['category'] . "', '" . $_POST['desc'] . "', '" . $_POST['image1'] . "')";
mysqli_query($connect, $query);
if(mysqli_query($connect, $query) || mysqli_query($connect, $sqlqr)) {
echo "<h4>1 record added</h4>";
}
else {
die('Error: ' . mysqli_error($connect));
}
print '</form>';
}
Unchecked values are not submitted and checkbox quantity not same with textbox.
You should give input name array same keys :
$i = 0;
while($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>";
echo "<input type=\"checkbox\" name=\"checkbox[".$i."]\" value=\"" . $sqlRow['artistId'] . "\"/> " . $sqlRow['firstname'] . " " . $sqlRow['lastname'] . "</td><td><input type=\"text\" name=\"textbox[".$i."]\"/></td>";
echo "</tr>";
$i++;
}
Use also this code:
$checkbox = $_POST['checkbox'];
$txt = $_POST['textbox'];
foreach ($checkbox as $key => $value)
$sqlqr = "INSERT INTO $role (artistId, movieCode, Description) VALUES ('" . $value . "', '" . $_POST['moviecode'] . "', '" . $txt[$key] . "')";
mysqli_query($connect, $sqlqr);
}
use mysql_escape_string($_POST['']) instead of the every field $_POST[''] in inside the mysqlquery.
As documented under 17.2.1 Control types:
When a form is submitted, only "on" checkbox controls can become successful.
In other words, the browser will only submit those checkbox controls that have been 'checked', yet will submit every textbox control irrespective of the status of the checkbox control with which you intended it to be associated.
Therefore, unless all checkbox controls were checked, the arrays $_POST['checkbox'] and $_POST['textbox'] created by PHP from the form submission will contain different numbers of elements—and, consequently, those with any given index may not match.
There are two ways of resolving this:
one can use client-side scripting to disable the textbox if the corresponding checkbox is unchecked: this will prevent the browser from submitting the textbox and, accordingly, the arrays in PHP will be aligned again (however note that this solution depends upon the availability of client-side script—you will have to test for and handle cases where such scripting is unavailable); or
one can give the controls explicit indexes to ensure that they are always aligned.
You also really ought to read up on proper string escaping (and how failure to do so exposes your application both to bugs and commonly exploited attack vectors): I thoroughly recommend #deceze's blog article, The Great Escapism (Or: What You Need To Know To Work With Text Within Text).
In particular, as he describes in his article, you should ensure that you escape any HTML in your variables before transmission to the browser (in order to prevent XSS attacks and bugs where the text to be output contains characters that have special meaning in HTML, for example <):
$result = mysqli_query($connect, "
SELECT artistId, CONCAT(firstname, ' ', lastname) AS fullname
FROM $artists
ORDER BY firstname
");
if ($result) {
echo '
<table class="addactor">
<tr>
<td id="text" colspan="2"><h3>Assign an actor to the movie</h3></td>
</tr>';
$i = 0;
while ($sqlRow = mysqli_fetch_array($result, MYSQL_ASSOC)) {
echo '
<tr>
<td>
<input type="checkbox"
name="checkbox[',$i,']"
value="', htmlentities($sqlRow['artistId']), '"
/>', htmlentities($sqlRow['fullname']), '
</td><td>
<input type="text" name="textbox[',$i,']"/>
</td>
</tr>';
$i++;
}
echo '
<tr>
<td align="right">
<input type="submit" name="submit" id="submit" value="Add">
</td><td>
<input type="reset" name="reset" id="reset" value="Reset">
</td>
</tr>
</table>';
}
Also, concatenating unescaped strings supplied by the user directly into your SQL not only makes you vulnerable to SQL injection attack, but furthermore introduces bugs where the strings contain characters that have special meaning within SQL string literals (for example ').
The solution is to prepare SQL statements with placeholders for parameters that get subsituted with your variables upon command execution; this also provides a performance boost since the statements need only be prepared once irrespective of the number of times that they are executed:
if ($_POST) {
$stmt = mysqli_prepare($connect, "
INSERT INTO $movies
(movieCode, title, dateOfIssue, category, description, image)
VALUES
(?, ?, ?, ?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'ssssss',
$_POST['moviecode'],
$_POST['title'],
$_POST['dateofissue'],
$_POST['category'],
$_POST['desc'],
$_POST['image1']
);
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
$stmt = mysqli_prepare($connect, "
INSERT INTO $role
(artistId, movieCode, Description)
VALUES
(?, ?, ?)
");
mysqli_stmt_bind_param($stmt, 'sss',
$checkbox,
$_POST['moviecode'],
$description
);
foreach ($_POST['checkbox'] as $i => $checkbox) {
$description = $_POST['textbox' ][$i];
mysqli_execute($stmt) or die('Error: ' . mysqli_error($connect));
}
echo '<h4>1 record added</h4></form>';
}

Update if variables exist else echo an error message?

How can I make this script to where if it finds that the fname and lname do not exist that it will pop up a message saying that they never signed in.
<?php
session_start();
include_once("connect.php");
date_default_timezone_set("America/Winnipeg");
$date = ("m-d-Y");
$timeout = date("g:i:s a");
if ("SELECT EXISTS(
SELECT *
FROM signin_out
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND date='" . $date . "')"
) {
mysql_query("
UPDATE signin_out
SET timeout='" . $timeout . "'
WHERE
lname='" . $_POST['lastname'] . "'
AND fname='" . $_POST['firstname'] . "'
AND timeout=''
");
header("Location: ../index.html");
} else {
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
}
?>
This is an intranet site for a highschool.
$sql = "SELECT COUNT(*) signedin FROM signin_out
WHERE lname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND fname = '" . mysql_real_escape_string($_POST['lastname']) . "'
AND date = '$date'";
$result mysql_query($sql) or die(myqsl_error());
$row = mysql_fetch_assoc($result);
if ($row['signedin'])) {
// update table
} else {
// Report not signed in
}
However, you really should switch to mysqli or PDO so you can use parametrized queries instead of concatenating strings, so you don't have to worry as much about escaping them.
This is only one part of the answer, #Barmar gave u how to handle the query itself.
Change
echo "<script type='text/javascript>'";
echo "alert('<p>Oops! You never signed in!</p><br><p>Please contact a
Librarian</p>');'";
echo "</script>'";
header('Location: ../index.php?notsignedin');
To
echo "<script type='text/javascript>'";
echo "alert('Oops!\nYou never signed in!\nPlease contact a
Librarian');'";
echo "window.location.href='../index.php?notsignedin';";
echo "</script>'";
The reason:
Strings which echo go into the web server buffer before being sent as a package to the browser.
This may cause your code to reach and do the header command, and then either you will redirect immediatly, or get an error message on the lines of '...you can not send headers after output...'
And seriously consider everybody's suggestion about PDO/Mysqli and using a more centralized/abstracted way to use the DB.
Check how many rows are returned by the query,if is more than 1 then fname and lname exists in database,you can also use count(*) but i won't to change your query :
$result = mysql_query("SELECT * FROM signin_out WHERE lname='".$_POST['lastname']."' AND fname='".$_POST['firstname']."' AND date='".$date);
$num_rows = mysql_num_rows($result);//count number of rows returned by query
if($num_rows >=1) {
//Update here
}
else {
//alert and redirect here
}
I understand that your site is for intranet use only , but i suggest to use PDO or Mysqli

Combine $_GET and $_POST in PHP?

for some friends and family (different sites), I created a script that allows them to input data into the database. With
echo ("<a href=\"./pagina.php?ID=" . $row['ID'] . "\">" . $row['ID'] . "<br>");
, I 'send' the ID of the requested table to the URL.
In pagina.php, I have this code:
ID: <?php echo $_GET["ID"]; ?>
That works, of course, but now I want to use that ID to also display the data from the database, so not from the URL. These values are " . $row['onderwerp'] . " and " . $row['tekst'] . "
(There may be more values to come, but I'm just a beginner, trying to get something to work).
I know this is possible, but I just can't get anything to work, as I have just started learning PHP.
I hope you can help me.
If you don't care whether data came from a $_COOKIE, $_GET, or $_POST, you can use $_REQUEST.
$id = (int)$_GET['id'];
$sql = "SELECT onderwerp, tekst FROM yourtable WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
echo "{$row['onderwerp']} - {$row['tekst']}<br />";
}

Combining two PHP variables for MySQL query

I have a variable formvar that is incremented every time a user adds an additional field in an HTML form. This variable is posted to the PHP script for the purpose of looping through all of the added fields.
I am trying to combine two variables in the MySQL query to match what is in my HTML form. I would like the MySQL query to go upc0, upc1, etc until the for loop terminates.
for($i=0;$i<=$_POST[formvar];$i++)
{
mysql_select_db("bits", $con);
$sql="INSERT INTO report (UPC, Quantity, Comment)
VALUES ('$_POST[upc].$i','$_POST[quantity].$i','$_POST[comment].$i')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else echo "Records added successfully";
}
Sorry if this code is bad, I am new to web programming.
Thank you!
Ok, since each answer hinted at escaping (but did not give an example):
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . mysql_real_escape_string($_POST["upc".$i]) . "','" .
mysql_real_escape_string($_POST["quantity" . $i]) . "','" .
mysql_real_escape_string($_POST["comment" . $i]) . "')";
That should protect you from SQL Injection, and is one proper method of creating sql queries. The best method would be to use parametrized queries (There's a ton of information out there on it, so I'd suggest a good Google search would be better than me trying to explain it here)...
First things first. In your HTML, create Input-Fields like this:
<input type="foo" name="upc[]">
<input type="foo" name="quantity[]">
<input type="foo" name="comment[]">
Then in your PHP-Script you do it like this:
<?php
# Choose DB
mysql_select_db("bits", $con);
# Iterates the Form-Data
$data_arr = array();
foreach($_POST['upc'] as $k=>$v) {
# Makes sure all needed data is available
if(isset($_POST['quantity'][$k], $_POST['comment'][$k])) {
$data_arr[] = array(
'upc' => $v,
'quantity' => $_POST['quantity'][$k],
'comment' => $_POST['comment'][$k]
);
}
}
# Build mysql insert string
foreach($data_arr as $k=>$v) {
# Escapes each field
$v = array_map('mysql_real_escape_string', $v);
# Maps array to value set
$data_arr[$k] = '('. implode(',', $v). ')';
}
$sql = 'INSERT INTO report (UPC, Quantity, Comment) VALUES '. implode(', ', $data_arr);
# Perform mysql query
mysql_query($sql, $con) or die('Error: ' . mysql_error());
echo 'Records added successfully';
Wrote it on my iPad, i'm on an airplane... so untestet. Good luck. ;o)
Not sure if I understand the question well but this is what I think :
$sql="INSERT INTO report (UPC, Quantity, Comment) VALUES
('" . $_POST["upc".$i] . "','" . $_POST["quantity" . $i] . "','" . $_POST["comment" . $i] . "')";
Note : this is a short version, you must add mysql_real_escape_string, etc, etc.
Also I supposed every variable could be string so I surrounded them by ''.
$_POST["name" . $i] let you loop throught POST variables starting with the name "name" followed by a number, this must be inserted into your for loop.
As recipes are so acclaimed I'm going to give my own, concerning the actual question:
<?php
for ($i=0; $i<=$_POST['formvar']; ++$i) {
mysql_select_db("bits", $con);
$v = array_map(mysql_real_escape_string(array(_POST["upc{$i}"], $_POST["quantity{$i}"], $_POST["comment{$i}"])));
$sql = "INSERT INTO report (UPC, Quantity, Comment) VALUES('"
. implode("', '", $v)
. "')";
if (!mysql_query($sql,$con)) {
trigger_error(html_entities('Error: ' . mysql_error()));
}
}
?>

the data can't display in the form

about my system the university complaint..stud or staff can use this system to complaint.
first user fill the form complaint and submit after submit user can view the complaint.now the problem is the complaint can't display....
this code for user complaint(userCampus.php):
?php // ------------------------------------------------------PROCESS -------------------------- START. ?>
<?php
$page_title='userCampus';
if(isset($_POST['submit'])){
if($_POST['secname']){
//$sn=escape_data($_POST['secname']);
$sn=$_POST['secname'];
// echo '<br> sn is : ' . $sn;
}else{
$sn=FALSE;
$message .='<p>You forgot to select section name!</p>';
}
if($_POST['subject']){
//$s=escape_data($_POST['subject']);
$s=$_POST['subject'];
}else{
$s=FALSE;
$message .='<p>you forgot to enter subject!</p>';
}
if($_POST['comment']){
//$c=escape_data($_POST['comment']);
$c=$_POST['comment'];
}else{
$c=FALSE;
$message .='<p>you forgot to enter comment!</p>';
}
}
if($sn && $s && $c ){
$userid = $_SESSION['username'];
$groupid = $_SESSION['secname'];
$query=" INSERT INTO campuscomplaint (secname, subject, comment, nameuser, groupid, userid)" .
" VALUES (" . "'" . $sn . "','" . $s . "','" . $c . "','" . $nameuser . "','" . $groupid . "','" . $userid . "')";
//echo 'query is : ' . $query . '<br>';
include "connectioncomplaint.php";
mysql_query($query);
echo'<p><b></b></p>';
include('done.php');
exit();
}
?>
<?php //------------------------------------------------ PROCESS ------------------------------------ end. ?>
<form action="<?php echo$_SERVER['PHP_SELF'];?>" method="post">
this code for view the complaint-userView.php(use for other page):
<?php //======================================================================================================================= PROCESS DATA ======================================================= START.
include "connectioncomplaint.php";
?>
<?php
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
//echo 'test : ' . $subject;
//Tarik data dari sini
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
//echo 'QUERY DETAIL :' . $queryDetail . '<br>' ;
$resultDetail = mysql_query($queryDetail);
//echo 'RESULT DETAIL :' . $resultDetail + 0 . '<br>' ;
$detail = mysql_fetch_array($resultDetail);
//echo $detail . '<br>';
//echo 'detail subject is : ' . $detail['subject'] . '<br>';
//echo 'detail comment is : ' . $detail['comment'] . '<br>';
//echo $detail[$x] . '<br>';
?>
i hope u all can help me....becoz i zero php.......
Let's see if we can check everything in on snip of code:
Paste the debugging code right after the line:
$detail = mysql_fetch_array($resultDetail);
Debugging code:
echo '<pre>';
echo '$userid = '.$userid."\n";
echo '$secname = '.$secname."\n\n";
echo 'Query: '.$queryDetail."\n\n";
echo 'Query results:'."\n\n";
print_r($detail);
echo '</pre>';
die();
That should make it clear where your problem is.
Also you should understand why you need to use mysql_real_escape_string() It's very important to make sure people don't do bad things to your website. Never send anything that can be changed by the user (such as GET or POST data) straight to a database without at least using this function. This escapes characters that would otherwise allow them to change your query (making it do something you don't want). To learn more about this google "sql injection attack"
one thing, from my experience. if something wrong with your query, just try it on mysql. ran your query in sql, and instead of your variables put some values, so you can easaly see what is your problem.
Looks like you forgot a $ sign before secname and you don't sanitize variables going to the query. So, try make it this way:
<?php
include "connectioncomplaint.php";
$userid = mysql_real_escape_string($_GET['userid']);
$secname = mysql_real_escape_string($_GET['secname']);
//Tarik data dari sini
$queryDetail = "SELECT * FROM campuscomplaint " .
"WHERE userid = '$userid' AND secname = '$secname'";
$resultDetail = mysql_query($queryDetail) or trigger_error(mysql_error()." in ".$queryDetail);
$detail = mysql_fetch_array($resultDetail);
?>
It looks you're not using a primary key on your campuscomplaint table, and using the various data fields as the identifier.
Since you say the data's inserted fine, you have to look at how you're retrieving it:
$userid = $_GET['userid'];
$secname = $_GET['secname'];
$subject = $_GET['subject'];
$comment = $_GET['comment'];
and then using these as your WHERE clause in the SQL query:
$queryDetail = " SELECT * FROM campuscomplaint " .
" WHERE subject = '" . $subject . "' AND comment = '" . $comment . "' ";
For one, this is vulnerable to SQL injection, and any $subject or $comment that contains single quotes will break the query. You are not checking to see if the query succeeded by calling mysql_error() after the mysql_query() call.
Also consider that you're retrieving these record "identifiers" from a GET query. These do have a limited length (different for various browsers). What if someone's comment is 10 kilobytes of data, but the browser will only send 1024 characters? Even if the database query succeeds, it will return no data because the comment fields will never match.
Let's say that the query string is limited to 100 characters (just for example purposes). You generate a list of complaints that looks something like this:
View complaint
Now remember, our query string is limited to 32 characters, so when the user clicks on the link, this is what will be sent to the server:
GET http://www.example.com/viewcomplaint.php?userid=7&secname=12&subject=This class sucks!!!&comment=Who hired this professor? He doesn't know a
and you'll end up with the following "identifiers"
$userid= 7;
$secname = 12;
$subject = "This class sucks!!!";
$comment = "Who hired this professor? He doesn't know a";
Notice how the $comment has been cut off. It will never match what is stored in the database, so your retrieval query will fail. Furthermore, notice that there is a single quote in it (doesn't). Inserting $comment into your query verbatim will now cause an SQL syntax error because of the imbalanced single-quote.
Add an auto_incrementing primary key field to your campuscomplaint table, like this:
ALTER TABLE campuscomplaint ADD id int unsigned not null auto_increment primary key;
and then all your complains can be identified by a single number, and you can retrieve them like this:
$id = (int)$_GET['id']; // force $id to be a number. better than just blindly using the value in a query
$query = "SELECT * FROM campuscomplaint WHERE id = $id;";
$result = mysql_query($query);
if (mysql_error()) {
// did the query fail? Say why!
die("MySQL query failed! Error cause: " . mysql_error());
}
etc....
The use of a numeric identifier will easily keep your query string very short (unless the people registering complaints file so many you get up into numbers hundreds or thousands of digits long).

Categories