Undefined index [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”
hello everyone i am getting a problem while updating my record..when i click the edit button it doesnot update the record but give following errors to all post variables.. i would really appreciate any kind of comments or help...
this is courses-edit.php
<?php include("../includes/config.php"); ?>
<?php
if ($_SESSION["isteacher"])
{
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$courseid=$_GET["id"];
$result = mysql_query("SELECT * FROM courses WHERE (id='".$courseid."')");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$title = $row['title'];
$des = $row['description'];
$subjectid = $row['subjects-id'];
}
mysql_close($con);
?>
<script type="text/javascript">
$(function() {
$("form").validity(function() {
$("#title")
.require("This Field Must Be Filled!!")
});
});
</script>
<?php include("../includes/header.php"); ?>
<?php include("includes/nav.php"); ?>
<div id="maincontent">
<div class="span-24 last">
<div id="breadcrumbs">
Home >
Manage Courses >
List Courses >
Edit Course
</div>
</div>
<?php include("../teacher/includes/manage-courses-aside.php"); ?>
<div class="span-18 last">
<h2 class="alt">Edit Course</h2>
<form id="form" method="post" action="courses-edit-action.php">
<input type="hidden" value="<?php echo $courseid; ?>" name="id" />
<label>Course Name:</label><input type="text" name="title" id="title" class="text" value="<?php echo $title; ?>" /><br /><br />
<label>Choose Subject:</label>
<?php
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT * FROM subjects");
echo "<select name='subjects-id'>\n";
while($row = mysql_fetch_array($result))
{
echo "<option value='".$row['id'] . "'";
if ($subjectid==$row['id'])
echo 'selected="selected"';
echo " >" . $row['subjectname'] . "</option>\n";
}
echo "</select>\n";
mysql_close($con);
?>
<label>Description:</label><textarea name="description" id="description"><?php echo $des; ?></textarea><br /> <br />
<input type="submit" value="Edit Course" class="button" />
</form>
<?php include("../includes/footer.php"); ?>
<?php
}
else
{
header("Location: ".$fullpath."login/unauthorized.php");
}
?>
and this is courses-edit-action.php
<?php include("../includes/config.php");?>
<?php
$id=$_POST["id"];
$title=$_POST["title"];
$des=$_POST["description"];
$subjectid=$_POST["subjects-id"];
$con=mysql_connect($dbserver,$dbusername,$dbpassword);
if (!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("ombts", $con);
$query=("UPDATE courses SET title='".$title."', description='".$des."', 'subjects- id'='".$subjectid."' WHERE (id='".$id."')");
$query=mysql_query($query);
if($result){
echo header("Location:manage-courses.php?status=2");
}
mysql_close($con);
?>
and the warnings are
Notice: Undefined index: id in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 4
Notice: Undefined index: title in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 5
Notice: Undefined index: description in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 6
Notice: Undefined index: subjects-id in C:\xampp\htdocs\project\teacher\courses-edit-action.php on line 7

You try to access
$id=$_POST["id"];
$title=$_POST["title"];
$des=$_POST["description"];
$subjectid=$_POST["subjects-id"];
this POST variables. But when you access the script for the first time this values are not set in the POST variable.
Chck the values with isset.
if(!isset($_POST["id"]) {
$_POST["id"] = '';
}
or safe the checked value in a new variable
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
for example.

Modify your script like this....
$id= isset($_POST["id"]) ?$_POST["id"] : 0 ;
$title= isset($_POST["title"]) ? $_POST["title"] : '' ;
$des=isset($_POST["description"]) ? $_POST["description"] : '';
$subjectid= isset($_POST["subjects-id"]) ? $_POST["subjects-id"] : '';
Edited
Also, i see an error here...
$query=mysql_query($query);
if($result){
should be
$result=mysql_query($query);
if($result){
If you still can't update the table, print the $query variable before you do mysql_query. Tell me what you see and i will help you.....

#Stony's answer is good solution to check if you are sending any POST data - and if not, do not try to fetch non-existing data.
Now, if you think $_POST["id"]; should be there, then there is something missing. Are you using GET instead of POST?
To see what data is submitted do a print_r($_POST). If this is blank, do a print_r($_REQUEST). If this is still blank, then no data is being submitted from the previous page.
You can also check by adding this in your URL &id=75 (or ?id=75 if you have no other parameters in the url). This will submit data and you will see one less error.

Related

Cannot change data on DB using form in PHP/HTML

I have a PHP generated HTML table that loads data from a MySQL database, in this table there is a button used to edit some information... When the button is pressed it sends the user to another page with a text field and a button.
The user can insert the new text and by pressing the button the new information should be stored in the DB, changing the old information with the new one…
But when I click the button to submit the new information, the following error appears:
Notice: Undefined index: ident in /...patch.../upload2.php on line 11
What I'm doing wrong? (I'm new to PHP)
Here is my code:
Resposta.php
<?php
ini_set('default_charset','UTF-8');
$con=mysqli_connect(“*******”,”*******”,”*******”,”*******”);
mysqli_set_charset($con,"utf8");
if (mysqli_connect_errno($con))
{
echo '{"query_result":"ERROR"}';
}
$emp_id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM prefeitura WHERE id = $emp_id") ;
while($row = mysqli_fetch_array($result))
{
if($row['ID']) {
echo '<p><b>ID: </b>'. $row['ID'] .'';
}
if($row['nome']) {
echo '<p><b>SOLICITANTE: </b>'. $row['nome'] .'';
}
if($row['rua']) {
echo '<p><b>RUA: </b>'. $row['rua'] .'';
}
if($row['bairro']) {
echo '<p><b>BAIRRO: </b>'. $row['bairro'] .'</p>';
}
if($row['problema']) {
echo '<p><b>PROBLEMA: </b>'. $row['problema'] .'';
}
echo '<br>';
if($row['solucionado']) {
echo '<br><p><b>SITUAÇÃO: </b>'. $row['solucionado'] .'';
}
}
echo '<br><br><form enctype="multipart/form-data" action="upload2.php" method="post">';
echo '<br><input type="text" class="input-text text-area" name="resposta" id="resposta" placeholder="Escreva a resposta" required/>';
echo '<input type="submit" class="input-btn" ident="' .$row['ID']. '" value="Enviar Resposta" />';
mysqli_close($con);
?>
upload2.php
<?php
ini_set('display_errors', true); error_reporting(E_ALL);
ini_set('default_charset','UTF-8');
$con=mysqli_connect(“*******”,”*******”,”*******”,”*******”);
mysqli_set_charset($con,"utf8");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$emp_id = $_POST['ident'];
$resposta = nl2br(htmlentities($_POST['resposta'], ENT_QUOTES, 'UTF-8'));
$result = mysqli_query($con,"UPDATE prefeitura SET solucionado = '$resposta' WHERE ID = '$emp_id';");
header('Location: mensagem_enviada.html');
?>
I managed to solve the problem: the ID value was not being sent when pressing the button...
here's the piece of code that worked:
$mudaid = $_GET['id'];
echo <<<HTML
<form enctype="multipart/form-data" action="upload2.php" method="post">
<br><textarea rows="10" cols="70" name="resposta" id="resposta"></textarea>
<br><button type="submit" name="ident" value="$mudaid">Enviar resposta</button>
HTML;
echo '</center>';
First of all, the problem:
Notice: Undefined index: ident in /...patch.../upload2.php on line 11
this is telling you there is no 'ident' in $_POST variable.
Check out if 'ident' is set when you send the form.
This is yours..
'<input type="submit" class="input-btn" ident="' .$row['ID']. '" value="Enviar Resposta" />';
You should do something like this->
(edited)
'';
You should adapt this in order to make it work. I might be missing a ' . ;
Then, another thing im seeing, you should not do this, you might be vulnerable to SQL INJECTION.
$result = mysqli_query($con,"UPDATE prefeitura SET solucionado = '$resposta' WHERE ID = '$emp_id';");
You should use prepare statements and PDO.
http://php.net/manual/en/pdo.prepared-statements.php

MySQL data not getting displayed in a PHP webpage

I'm trying to get some data from MySQL to be displayed on a PHP webpage but no data is getting displayed.
I have the variables searchterm and searchtype declared higher up in the HTML code. The HTML code only has an option of a drop down menu and an option for the user to search.
When I run the code however, no data is displayed. All I get is: "Number of projects found:" which is where the data is meant to be displayed.
The full HTML and PHP code that I have is shown below.
<html>
<body>
<h1>Search</h1>
<form action="list_projects.php" method="POST">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="projectNo">Project Number</option>
<option value="pjname">Project Name</option>
<option value="city">Project City</option>
</select>
<br />
<p>Enter Search Term: </p>
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
$hostname='mysql.uniwebsite.ac.uk';
$database='somedatabase';
$username='uniusername';
$password='unipassword';
$link = mysqli_connect($hostname, $username, $password);
if (!$link) {
die('Connection failed: ' . mysqli_error());
}
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
$query = "select * FROM tables WHERE ".$searchtype." like '%".$searchterm."%'";
$result = mysqli_query($link, $query);
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Project Number: ";
echo htmlspecialchars(stripslashes($row['projectNo']));
echo "</strong><br />Project Name: ";
echo stripslashes($row['pjname']);
echo "<br />Project City: ";
echo stripslashes($row['city']);
echo "</p>";
}
$mysqli_free_result($result);
$mysqli_close($link);
?>
</body>
</html>
The following errors are what I get when I turn error reporting on:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /home/list_projects.php on line 39
Number of projects found:
Notice: Undefined variable: mysqli_free_result in /home/list_projects.php on line 52
Fatal error: Function name must be a string in /home/list_projects.php on line 52
Some improved code to help you on your way, see the Change: and Homework: lines:
<html>
<body>
<h1>Search</h1>
<form action="list_projects.php" method="POST">
<p>Choose Search Type: <br /></p>
<select name="searchtype">
<option value="projectNo">Project Number</option>
<option value="pjname">Project Name</option>
<option value="city">Project City</option>
</select>
<br />
<p>Enter Search Term: </p>
<input name="searchterm" type="text" size="20"/>
<br />
<input type="submit" name="submit" value="Search"/>
</form>
<?php
// Change 1: Enable error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
$hostname='mysql.uniwebsite.ac.uk';
$database='somedatabase';
$username='uniusername';
$password='unipassword';
// Change 2: Add $database
$link = mysqli_connect($hostname, $username, $password, $database);
// Change 3: Literally copy&paste error checking from mysqli_query docs page
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// Homework: Check for legal values in more detail
$searchtype=$_POST['searchtype'];
$searchterm=trim($_POST['searchterm']);
if (!$searchtype || !$searchterm) {
echo 'No search details. Go back and try again.';
exit;
}
// Homework: Use prepared statements to avoid sql injection
$query = "select * FROM tables WHERE ".$searchtype." like '%".$searchterm."%'";
// Change 4: Error checking
if ($result = mysqli_query($link, $query))
{
$num_results = mysqli_num_rows($result);
echo "<p>Number of projects found: ".$num_results."</p>";
for ($i=0; $i <$num_results; $i++) {
$row = mysqli_fetch_assoc($result);
echo "<p><strong>".($i+1).". Project Number: ";
echo htmlspecialchars(stripslashes($row['projectNo']));
echo "</strong><br />Project Name: ";
echo stripslashes($row['pjname']);
echo "<br />Project City: ";
echo stripslashes($row['city']);
echo "</p>";
}
// Change 5.1: Remove $
mysqli_free_result($result);
} else {
printf("Error: %s\n", mysqli_error($link));
}
// Change 5.2: Remove $
mysqli_close($link);
?>
</body>
</html>

insert values from multiple checkbox into database PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
handling checked checkboxes PHP
i have this problem. I have a webpage that show car registration number and it's violation. And we can change the status of the violation from 1=not treated to 2=treated. I want to use multiple check box to choose which car registration status that i want to change
here's the screenshot of my web
)
how i change the status of both car registration number ?
here's my webpage code
<div id="content">
<div class="content_item">
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$query = "SELECT * FROM laporan WHERE status = '1'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{?>
<form action="ubahdata.php" method="post">
<input type="checkbox" name="idlaporan" value="<?php echo $row['idlaporan'] ?>" /><?php echo "ID : {$row['idlaporan']}" ?><br />
<?php echo "Nomor Polisi : {$row['platkendaraan']} <br>" .
"Status : {$row['status']} <br>" .
"Tanggal Laporan : {$row['tanggallapor']} <br><br>"; ?>
<?php
}
?>
<input type="submit">
</form>
and here's my script
<?php include 'header.php'; ?>
<?php
$con = mysql_connect("localhost","fpjarmul","fpjarmul");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("fpjarmul", $con);
$sql=("UPDATE laporan set status='2' where idlaporan='$_POST[idlaporan]'");
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
<?php include 'footer.php'; ?>
Please try the following approach:
Change the checkbox 'name' as 'idlaporan[]' (<input type="checkbox" name="idlaporan[]" )
After form submit, selected check box values will be present in the Server side array $_POST['idlaporan']
Use a foreach loop to update values in database.
foreach ($_POST['idlaporan'] as $idlaporan) {
$sql=("UPDATE laporan set status='2' where idlaporan='$idlaporan'");
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
}
echo "1 record added<br/>";
}

PHP Issue with deleting from MySQL

I do have programming experience, but new to php. I do have an issue with an example I was doing from this tutorial. I looked over it millions of times, googled, ect ect. I don't have an idea why my code isnt working.
The purpose is to basically just test inserting and deleting in sql from php, using a button for Add Record and Delete Record. The Add record button works perfectly, but delete doesnt do a thing other than reload the page. Heres the code...
<?php // sqltest.php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['type']) &&
isset($_POST['year']) &&
isset($_POST['isbn']))
{
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
if (isset($_POST['delete']) && $isbn != "")
{
echo "worked!!!!!!!!!!!!!!";
$query = "DELETE FROM classics WHERE isbn='$isbn'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
//if (!mysql_query($query, $db_server))
//echo "DELETE failed: $query" . mysql_error();
}
else
{
echo "nooooooooooooooooooo";
$query = "INSERT INTO classics VALUES" .
"('$author', '$title', '$type', '$year', '$isbn')";
if (!mysql_query($query, $db_server))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
echo <<<_END
<form action="sqltest.php" method="post"><pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre></form>
_END;
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
$rows = mysql_num_rows($result);
for ($j = 0 ; $j < $rows ; ++$j)
{
$row = mysql_fetch_row($result);
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Type $row[2]
Year $row[3]
ISBN $row[4]
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="$row[4]" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
_END;
}
mysql_close($db_server);
function get_post($var)
{
return mysql_real_escape_string($_POST[$var]);
}
?>
I have looked over this many times, still no idea why this won't work. Is it the for loop that is making this button not work? Note, you will see echo "worked!!!"; and in the else echo "noooooooo"; that was for me to test whether the button was being tested, yet nothing prints. So maybe i missed something in the button code itself? Also, no errors are printed, and my editor (and myself) have missed the syntax error (if thats the case).
The code for the delete button is at the end, before I closed the DB.
Thanks for your help in advance.
Your problem is your first if block.
You're checking for the presence of the posted variables author title type year isbn. Whereas in your delete code the only variables sent are delete and isbn. Therefore the first if block is completely missed (including the delete code).
You need to modify your first if to be if(isset($_POST)) { // a form has been posted. Then it should work.
Another way to do it:
if(isset($_POST['delete']) && isset($_POST['isbn']) && !empty($_POST['isbn'])){
//delete code here
}
if(isset($_POST['author']) && isset($_POST['title']) && isset....){
// insert code here
}
EDIT: rewritten code:
<?php // sqltest.php
// I don't know what's in here, so I've left it
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database, $db_server)
or die("Unable to select database: " . mysql_error());
if (isset($_POST))
{
if (isset($_POST['delete']) && !empty($_POST['isbn']))
{
echo "Deleting";
$query = "DELETE FROM classics WHERE isbn='".mysql_real_escape_string($_POST['isbn'])."'";
$result = mysql_query($query) or die(mysql_error());
if(mysql_affected_rows($result) > 0) echo 'user deleted';
}
else
{
echo "Inserting";
$query = "INSERT INTO classics VALUES ('".mysql_real_escape_string($_POST['author'])."', '".mysql_real_escape_string($_POST['title'])."', '".mysql_real_escape_string($_POST['type'])."', '".mysql_real_escape_string($_POST['year'])."', '".mysql_real_escape_string($_POST['isbn'])."')";
if (!mysql_query($query))
{
echo "INSERT failed: $query" . mysql_error();
}
}
}
// you don't need echo's here... just html
?>
<form action="sqltest.php" method="post">
<pre>
Author <input type="text" name="author" />
Title <input type="text" name="title" />
Type <input type="text" name="type" />
Year <input type="text" name="year" />
ISBN <input type="text" name="isbn" />
<input type='submit' value='ADD RECORD' />
</pre>
</form>
<?php
$query = "SELECT * FROM classics";
$result = mysql_query($query);
if (!$result) die ("Database access failed: " . mysql_error());
// a better way to do this:
while($row = mysql_fetch_array($result)){
?>
<pre>
Author <?php echo $row[0]; ?>
Title <?php echo $row[1]; ?>
Type <?php echo $row[2]; ?>
Year <?php echo $row[3]; ?>
ISBN <?php echo $row[4]; ?>
<form action="sqltest.php" method="post">
<input type="hidden" name="delete" value="yes" />
<input type="hidden" name='isbn' value="<?php echo $row[4]; ?>" />
<input type='submit' value='DELETE RECORD' />
</form>
</pre>
<?php
}
mysql_close($db_server);
?>
Verify the method you used in your form. Make sure it's POST like this:
Form action="yourpage.php" method="POST"
and in your code above, replace the following:
$author = get_post('author');
$title = get_post('title');
$type = get_post('type');
$year = get_post('year');
$isbn = get_post('isbn');
with
$author = $_POST['author'];
$title = $_POST['title'];
$type = $_POST['type'];
$year = $_POST['year'];
$isbn = $_POST['isbn'];
Finally, there is no need to check again if the $isbn is not null as you did it in your isset() method. So remove $isbn!="" in the if below:
if (isset($_POST['delete']) && $isbn != "")
{
}
becomes:
if (isset($_POST['delete']))
{
}
Since you are testing, checking if the user clicked the delete button is of less importance. So you can also remove it for a while and add it later because you are sure that, that code is accessible after clicking the delete button.
You have no form field named delete, so it is impossible for your delete code path to ever be taken.
I'm guessing you're tryign to use the value of the submit button to decide what to do? In that case, you're also missing a name attribute on the submit button - without that, it cannot submit any value with the form. You probably want:
<input type="submit" name="submit" value="DELETE RECORD" />
and then have
if (isset($_POST['submit']) && ($_POST['submit'] == 'DELETE RECORD')) {
...
}

advice on php post operation not running

I have donation page which when the user clicks donate it posts the data to a php file named test.php I am trying this out my first trying to echo the first name and last name but this is not working ultimately I want this php page to run a MySQL query to update the total_Donation row within a database, here is my main php page first.
Database code which sits at top of file
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
$rsNames= mysql_fetch_assoc($names_query);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$donation = mysql_real_escape_string($_GET['donation']);
$fname = mysql_real_escape_string($_GET['first_Name']);
$lname = mysql_real_escape_string($_GET['last_Name']);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '{$donation}' WHERE first_Name = '{$fname}' AND last_Name = '{$lname}'";
}
mysql_close($con);
?>
Here is my form section of html
form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select>
<?php do{?>
<option> <?php echo $rsNames['first_Name'];?> <?php echo $rsNames['last_Name'];?></option>
<?php } while ( $rsNames= mysql_fetch_assoc($names_query))?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation"/></td></tr>
<tr><td><input id="submit" type="submit" value="DONATE"/></td></tr>
</table>
</form>
the option gets all the first names and last names fine when the user hits donate I want it to run the $donation_sql but all i get are errors saying unidentified index, I'm even trying the below in the test.php to simply just echo the first_Name this is giving the same error.
<?php
echo $_POST['first_Name'];
?>
Can someone please help me with this, thanks.
index.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
$names_sql = "SELECT first_Name, last_Name FROM donate WHERE user_ID > 0";
$names_query = mysql_query($names_sql)or die(mysql_error());
?>
<form method ="post" action="test.php">
<table>
<tr><td><label>Runner:</label></td>
<td>
<select name="name">
<?php
while($list = mysql_fetch_array($names_query))
{
?>
<option value="<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>">
<?php echo $list['first_Name'] . ' ' . $list['last_Name']; ?>
</option>
<?php
}
?>
</select>
</td>
</tr>
<tr><td><label>Donation £</label></td><td><input type="text" maxlength="9" value="0.00" name="donation" /></td></tr>
<tr><td><input id="submit" type="submit" name="send" value="DONATE"/></td></tr>
</table>
</form>
test.php
<?php
$con = mysql_connect("localhost","root","null");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("snr", $con);
if(isset($_POST['donation']) && $_POST['donation'] != '')
{
$names = explode(' ',$_POST['name']);
$first_name= $names[0];
$last_name= $names[1];
$donation = mysql_real_escape_string($_POST['donation']);
$fname = mysql_real_escape_string($first_name);
$lname = mysql_real_escape_string($last_name);
$donate_sql = "UPDATE `donate` SET donate_Total = donate_Total + '" .$donation. "' WHERE first_Name = '" .$fname. "' AND last_Name = '" .$lname. "'";
echo 'DEBUG (remove after OK): <br>' .$donate_sql. '<br>';
$res = mysql_query($donate_sql);
echo 'Thanks ' .$first_name. ' ' .$last_name. '<br>';
}
mysql_close($con);
?>
That´s it!
\make sure you set name for select and you have valua attr in option tag
<select name="first_Name">
<otpion value="<?php echo $rsNames['first_Name'];?>"><?php echo $rsNames['first_Name'];?>
<?php echo $rsNames['last_Name'];?>
</option>
</select>
YOu need to give a name attribute to the select:
<select name="first_Name">
<?php while ( $rsNames= mysql_fetch_assoc($names_query)):?>
<option value="<?php echo htmlspecialchars($rsNames['first_Name']).' '.htmlspecialchars($rsNames['last_Name']);?>"> [option displayed to the user here]</option>
<?php endwhile;?>
</select>
And of course use the $_POST array, not the $_GET, since you're using the POST method.

Categories