I need some help. I have written a script to put first and last name into a database. This works correctly. Then I have written a script to display these names along with 4 text fields per name where student points can by typed in and then stored in the DB. The names from the DB are displayed correctly and the text fields display correctly however, when I try to put the numbers in the fields it does not put the numbers in the DB and generates "undefined index" errors. I have worked on this for a while but am just not getting it. Thanks for your help. My code is below. Thank you.
<html>
<body>
<form action="pts_summary.php" method="post">
<table border="1">
<tr>
<th>Student Name</th>
<th>First Hour</th>
<th>Second Hour</th>
<th>Third Hour</th>
<th>Fourth Hour</th>
</tr>
<br>
<?php
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$con=mysqli_connect("localhost","root","","srrdb");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * From students");
while($row = mysqli_fetch_array($result))
{
echo "<tr>"."<td>".$row['fname']." ".$row['lname']."</td>".
"<td>".'<input type="text" name="hour1">'."</td>".
"<td>".'<input type="text" name="hour2">'."</td>".
"<td>".'<input type="text" name="hour3">'."</td>".
"<td>".'<input type="text" name="hour4">'."</td>"."</tr>";
}
if (isset ($_POST['submit']))
{
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
mysqli_close($con);
?>
</table>
<br><input type="submit" value="SUBMIT" name="submit">
</form>
</body>
</html>
You're trying to grab post data before you even check if the submit button was pressed. If the submit button wasn't pressed, you won't have values in any of the $_POST['hour#'] fields, and that will throw an undefined index error. Throw those lines AFTER the submit check like so.
if (isset ($_POST['submit']))
{
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
}
Your undefined index notices are caused by using $_POST[...] without checking if they are set. Your data is not inserting into your database, as you are only setting the INSERT query -
$sql="INSERT INTO students...
but you never execute a query.
mysqli_query($con,$sql);
try -
if (isset ($_POST['submit'])){
// put these inside isset() to prevent undefined index notices
$hour1 = $_POST['hour1'];
$hour2 = $_POST['hour2'];
$hour3 = $_POST['hour3'];
$hour4 = $_POST['hour4'];
$sql="INSERT INTO students (hour1, hour2, hour3, hour4)
VALUES ('".$hour1."','".$hour2."','".$hour3."','".$hour4."')";
//missing the query line
// Insert or die with error message
$update = mysqli_query($con,$sql) or die(mysqli_error($con));
}
Also, you are using unsanitized $_POST data so you are open to SQL Injection. Either sanitize using mysqli_real_escape_string() or better yet use prepared statements - http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
Related
I have a search form where the user will insert his/her CODE and NAME & TELEPHONE of that CODE will then be shown inside a table which is working fine (Thanks to stack overflow).
<form action="list25.php" method="post">
Search By code:<input type="text" name="code"><br><br>
<table border="0" width="100%" cellpadding="0" cellspacing="0" id="product-table">
<tr>
<th class="table-header-repeat line-left">Name</th>
<th class="table-header-repeat line-left">telephone</th>
</tr>
<?php
if (isset($_POST['search'])) {
$code = $_POST['code'];
$connect = mysqli_connect("localhost", "root", "", "sahmiye");
$query = "select * from balance where code = $code ";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['telephone']; ?></td>
</tr>
<?php
}
} else {
echo "Undifined ID";
$name = "";
$telephone = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$name = "";
$telephone = "";
}
?>
</table>
<br><br>
<input type="submit" name="search" value="Find">
</form>
BUT i have a second completely different form as well and when the user writes his/her CODE in this second form i needed the NAME & TELEPHONE of that CODE to then be shown inside textboxes and the user will then fill up the rest of the form and then submit it so it can be saved into the database.
The problem being i know i cant have a form within a form but is there a way for me to run my first search form shown above with out using a form so that i can have the same function inside my second form whereby after CODE is given , it will fill up the textboxes with the NAME & TELEPHONE of that CODE ?
Display data from database without using form tags?
You need to use a GET array and use the parameter in the href.
I.e. and checking if it is set and not empty and equal to "something":
Name
Then use the GET array with the parameter.
if(!empty($_GET['var']) && $_GET['var'] == 'John'){
// do your thing to search for the string "John", as an example.
// ATT'N: John and john in the database are two different animals.
}
Use the same format for the other href.
Sidenote: Remove the href's from inside the <form></form> tags, as it may cause some havoc.
You will also need to quote the variable in the query when it is a string.
I.e.:
$query = "select * from balance where code = '$code' ";
...if $code is a string.
However, it will throw an error if the query contains characters that MySQL will complain about such as John's Bar & Grill, therefore a prepared statement/escaping the value will be required and will help prevent a possible SQL injection at the same time.
Reference:
https://en.wikipedia.org/wiki/Prepared_statement
Edit:
Going over the question again and TBH is a bit complicated, using sessions would be something to use in order to keep the values.
http://php.net/manual/en/session.examples.basic.php
...then checking if any of the session array(s) is/are set and not empty.
N.B.: session_start(); must reside inside all pages using sessions in order for this to work. Inputs can also contain sessions-related code and "if set/not empty". Otherwise, you will get errors about them being undefined.
I'm after a little help. I have a page for a user to input upto 10 different rows of information. Dispatch details. I have created a page with my form using a loop..
<?php
session_start();
require("config.php");
require("header.php");
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
<br><br><br></br>
<form action="insertdispatch.php" method="post">
<body>
<center>
<table>
<tr>
<td><center><b>Ref</td>
<td><b><center>Date</td>
<td><b><center>Service</td>
<td><b> <center>Tracking</td>
</tr>
<?php
$index = 1;
$name = 1;
while($index <= 10){
?>
<td><input type="text"
name="transno<?php echo $index;?>"
id="transno<?php echo $index;?>" />
</td>
<td><input type="text" name="date<?php echo $index;?>"
id="date<?php echo $index;?> "/>
</td>
<td><select name = "service<?php echo $index;?>"><?php
$viewsql = "SELECT * FROM dispatch_service ORDER BY service ASC";
$viewresult = mysql_query($viewsql);
while($row = mysql_fetch_assoc($viewresult)){
?> <option value=<?php echo $row['service'] ;?>>
<?php echo $row['service'] ;?></option>
<?php
}
echo "</select>";?>
<td><input type="text"
name="tracking<?php echo $index;?>"
id="tracking<?php echo $index;?>"/>
</td>
</tr>
<?php $index ++;
}?>
<center>
<td><input type="submit" value="Add Product" />
</form>
</center>
</td>
</tr>
</table>
</center>
<center><a href='javascript:history.back(1);'>Back</a>
</body>
</html>`
I have 10 of each text box, the name of the text box adds the value of index to the end. (with my limited coding experience I am very pleased with myself) so I go to the insertdispatch.php page and the plan is to insert each of these values into my table... now...I have no clue... and I cannot seem to figure out how I am going to do this...
I think I will need to use a loop again.. but I can't seem to figure out how I am going to call each of the $_POST values. I don't really want to use 10 different insert statements, as the form may increase in size. here is what I have so far..
<?php
session_start();
require("config.php");
$db = mysql_connect("localhost","root","");
if (!$db)
{
do_error("Could not connect to the server");
}
mysql_select_db("hbt",$db)or do_error("Could not connect to the database");
$index = 1;
while($index <= 10){
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking) values ()";
mysql_query($insertsql);
$index ++;
}
//header("Location: " . $config_basedir . "home.php");
?>
I am not looking for anyone to finish the coding for me, but any tips would be grateful! :)
you can build 1 insert statement that inserts multiple rows:
INSERT into dispatch (trans_no, date, service, tracking) values
(1, '2013-09-12', 'myService1', 'on'),
(1, '2013-09-12', 'myService2', 'on'),
(1, '2013-09-12', 'myService3', 'on'),
(1, '2013-09-12', 'myService4', 'on'),
(1, '2013-09-12', 'myService5', 'on');
Just build this inside your the while, and execute it after the while has finished.
To build this query, you will need to perform the exact same loop as when you are generating the HTML, but now just fetch the values from $_POST instead of create a html field for them...
note while building your HTML, you are firing a static query inside your for loop. since this query is static, the results will also not change, and it is best to execute that query outside of the outer while loop.
(you really should read up more on basic HTML - tehre are lots of mistakes there even before considering the PHP code).
name="transno<?php echo $index;?>"
This is really messy too - you are creating extra work and complication for yourself. Use arrays:
name="transno[]"
If you do exlpicitly want to reference the item again then set the index:
id="transno[<?php echo $index; ?>]"
And at the receiving end....use a single insert statement to add the rows - not 10 seperate ones (it will be much faster).
You've already set up your while loop with $index - you could simply use that to iterate through the POST values, since you set their name attribute with an index. Consider:
$index = 1;
while($index <= 10){
$trans_no = $_POST["transno$index"];
$service = $_POST["service$index"];
$date = $_POST["date$index"];
$tracking = $_POST["tracking$index"];
$insertsql = "INSERT into dispatch (trans_no, date, service, tracking)
VALUES($trans_no, $date, $service, $tracking)";
mysql_query($insertsql);
$index++;}
Though it would be much cleaner to set up your form inputs as arrays, as noted by others here.
Also, please read up on SQL injection. You need to sanitize any user input before it's inserted into a database - otherwise a malign user could wipe your whole database.
I'm working on updating text to sql.
I am facing problem in my code below not updating the db, but when i change the where pid='$data[pid]' statement to some index like where pid='3', it works.
I'm new in programming. can you explain why?
thanks.
<?php
//include "koneksi.php";
$host="localhost";//nama server
$user="root";//username
$pass="";//password
$dbnama="skripsi";//nama database yang dipilih
mysql_connect($host, $user, $pass) or die ("Database tidak dapat di akses");//koneksi ke database
mysql_select_db($dbnama); //database yang dipilih
?>
<?php
$query="select pid, username, user, datapos, datanet, dataneg, status from trainklasifier";
$hasil=mysql_query($query);
?>
<html>
<head>
</head>
<body>
<table border="1" align="center">
<tr>
<td >ID</td>
<td >Model Klasifikasi</td>
<td >Creator</td>
<td width="300px">Data Positif</td>
<td width="300px">Data Netral</td>
<td width="300px">Data Negatif</td>
<td width="100px">Status</td>
<td width="100px">Aksi</td>
</tr>
<?php
$datapos=$data[datapos];
$datanet=$data[datanet];
$dataneg=$data[dataneg];
$dataid=$data[pid];
while ($data=mysql_fetch_array($hasil)){
echo ("<tr><form id='form1' action='' method='post'>
<td><textarea rows='1' cols='1' name='taid' value='$dataid' disabled>$data[pid]</textarea></td>
<td>$data[username]</td>
<td>$data[user]</td>
<td><textarea rows='4' cols='35' name='tapos' >$data[datapos]</textarea></td>
<td><textarea rows='4' cols='35' name='tanet' value='$datanet'>$data[datanet]</textarea></td>
<td><textarea rows='4' cols='35' name='taneg' value='$dataneg'>$data[dataneg]</textarea></td>
<td>$data[status]</td>
<td><input type='submit' name='btsubmit' value='Train' /></td>
</form></tr>");}
?>
<?php
$inputpos=$_POST['tapos'];
$inputnet=$_POST['tanet'];
$inputneg=$_POST['taneg'];
$id=$_POST['taid'];
if (isset($_POST['btsubmit'])){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
mysql_query("update trainklasifier set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg' where pid='$data[pid]'");
}
echo $inputpos;
?>
</table>
</body>
</html>
If you use arrays inside string interpolation you need to wrap then in {}
For example
"where pid = '{$data['pid']}'"
Also, it appears you are not quoting your array keys. $data[key] should be either $data["key"] or $data['key'] unless you are using a variable, as in $data[$key]
I feel that $data['pid'] may be wrong. Consider:
$datapos=$data[datapos];
$datanet=$data[datanet];
$dataneg=$data[dataneg];
$dataid=$data[pid];
...here $data is okay, I assume...
while ($data=mysql_fetch_array($hasil)){
...here you cycle $data, and so exit when $data is NULL...
<td><input type='submit' name='btsubmit' value='Train' /></td>
</form></tr>");}
^---
Here you have closed the cycle (I'd use a HERE-document if I were you, BTW), and so
from now on $data is NULL.
$id=$_POST['taid'];
Here you have retrieved $id.
if (isset($_POST['btsubmit'])){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
mysql_query("update trainklasifier set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg' where pid='$data[pid]'");
And here you use $data[pid] which does not exist. The syntax would actually work, it is not too clear ({$data['pid']} would be better), but the problem is that $data is no longer an array here.
You probably want to use $id instead:
$query = <<<QUERY1
update trainklasifier
set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg'
where pid='$id';
QUERY1;
mysql_query($query);
Checking _POST
The POST checking code, if it is in the same file, ought to be enclosed in a suitable check that a POST was indeed originated:
<?php
$need = array('tapos','tanet','taneg','taid','btsubmit');
$haveAll = true;
foreach($need as $fld)
if (!isset($_POST[$fld]))
$haveAll = false;
if ($haveAll) {
// Now we can proceed with POST.
$inputpos=$_POST['tapos'];
$inputnet=$_POST['tanet'];
$inputneg=$_POST['taneg'];
$id=$_POST['taid'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("skripsi") or die(mysql_error());
// This is a here-document. Things to check: no two identifiers in the
// same PHP file (use QUERY1, QUERY2, ...). No spaces around the first
// opening tag ("<<<QUERY"). The closing tag and the semicolon must be
// the only thing on the closing line, no spaces, nothing: "QUERY1;"
// (These conditions are more restrictive than necessary: to be safe).
$query = <<<QUERY1
update trainklasifier
set datapos='$inputpos',datanet='$inputnet',dataneg='$inputneg'
where pid='$id';
QUERY1;
mysql_query($query) or die(mysql_error());
}
Try this change update query like this
mysql_query("update trainklasifier set datapos='".$inputpos."',datanet='".$inputnet."',dataneg='".$inputneg."' where pid='".$data[pid]."' ");
I've ran into a wall at the moment, This code brings up a table with a button on the end of each record. Once pressed this then does a function to UPDATE the Health record by -5.
This works great for the job but it effects all rows, I've tried to get it to only touched one record via the ID but no luck! if you can help that would be great!
the php
$sql="SELECT `id` , `FirstName` , `Health` FROM ajax_demo WHERE `id` = `id` LIMIT 0 , 30";
$result = mysql_query($sql);
if(isset($_REQUEST['submit']))
{
counterminus();
}
function counterminus()
{
$cmeter = $cmeter - 1;
$id = $_POST["id"];
$FirstName = $_POST["FirstName"];
mysql_query("UPDATE ajax_demo SET `Health` = `Health` - `Damage` WHERE id = {$id}");
Header("location:oo_test.php");
}
This is the php / form
<?php
echo
"<table border='1'>
<tr>
<th>id</th>
<th>Firstname</th>
<th>health</th>
</tr>";
while($row = mysql_fetch_row($result)) {
echo '<tr>';
foreach($row as $cell) {
echo "\n<td>$cell</td>";
}
echo '<td><form id="theForm" action="" method="POST" >
<input type="submit" name="submit" id="submit" value="Attack" />
<input type="hidden" name="'.$row[1].'" /></form></td></tr>';
echo "\n\n";
}?>
This is vunerable to attack through the $_POST['id'] variable. Use mysql_real_escape_string, or better, prepared queries through PDO or MySQLi, anyway this is orthogonal to the issue you are having, it's just a good idea to be aware of it.
You're never actually submitting a HTML form field with the name id. In addition, in your HTML, $row will be NULL outside of your while loop, so will be undefined in the first place. This will mean that the name of your hidden field will be blank, and that your SQL is saying UPDATE WHERE id=, which is invalid and will cause an error.
To fix, you need to submit a form field with the name "id" such that $_POST['id'] actually contains a value.
Why did you write {id} instead of $id ?
Plus your code is totally unsafe and could be easily altered and hacked.
You should try PDO instead of mysql_query which is also depreciated.
http://php.net/PDO
I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.