Inserting specific values into a DB, and displaying it on a table? - php

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.

Related

Table with database values and user input

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!
Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

Display data from database without using form tags?

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 using PHP and need to Insert into sql using a while loop

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.

Entering secondary data into pre-existing database

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']."&nbsp".$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

Update mysql database fields with array php

I'm trying to achieve a multiple update in one submit. I have a table with a number of rows and want to be able to update one field in each row just by tabbing to the next insert box.
My code is thus:-
//start a table
echo '
';
//start header of table
echo '<tr>
<td width="60" align="center"><strong>Lab Item ID</strong></td>
<td width="60" align="center"><strong>Test Suite Name</strong></td>
<td width="60" align="center"><strong>Test Name</strong></td>
<td width="50" align="center"><strong>Result</strong></td>
</tr>';
//loop through all results
while ($row=mysql_fetch_object($sql)) {
//print out table contents and add id into an array and email into an array
echo '<tr>
<td align="center"><input name="id[]" value='.$row->lab_item_id.' readonly> </td>
<td align="center">'.$row->test_suite_name.'</td>
<td align="center">'.$row->test_name.'</td>
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
</tr>';
}
//submit the form
echo'<tr>
<td colspan="3" align="center"><input type="submit" name="Submit" value="Submit"></td>
</tr>
</table>
</form>';
//if form has been pressed proccess it
if($_POST["Submit"])
{
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
foreach( $_POST['id'] as $id ) {
$tresult = trim($_POST['test_result']);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
var_dump($tresult);
//redirect user
$_SESSION['success'] = 'Updated';
//header("location:index.php");
}
?>
When I print the $_POST arrays, everything is populating fine, however the variable is Null. I know I can't do a foreach on multiple arrays (at least I don't think I can) so is there some other trick I'm missing please? I can't be far away as the $_Post print has the right data in it.
Incidentally, the whole thing is generated by a query, so I never know how many records I'll have to update.
I've been looking at this (and other) forums, but can't seem to get a solution. I thought I understood arrays, but now I'm beginning to wonder!
edit - it's the $tresult variable that isn't working.
Many thanks,
Jason
Edit Thursday 21st Feb (05:41 UK time)
Thanks for your input everybody. I've solved this one now, and your collective advice helped. The code that finally cracked it is:-
//get data from form
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach ($id1 as $key => $value){
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id=$value ";
//execute query
Working through which variables etc were populated and what they were populated with was the key. Back to first principles, isn't it?
Cheers all.
J
Actually, you might get it done by doing a simpler (basic) form of for loop:
//get data from form
//$name = $_POST['name'];
//$_POST['check_number'] and $_POST['check_date'] are parallel arrays
$numberOfData = count($_POST['id']);
for($index = 0; $index < $numberOfData; $index++)
{
$id = $_POST['id'][$index];
$tresult = trim($_POST['test_result'][$index]);
$query = "UPDATE tbl_lab_item SET test_result='$tresult' WHERE lab_item_id = '$id'";
//execute query
}
print_r($_POST);
I hope this helps.
Cheers
change the query like this :
$query = "UPDATE tbl_lab_item SET test_result=$tresult WHERE lab_item_id = $id";
By adding single quotes ' ' you tell it to read is as a String and not to take the value of the var.
Edit
Replace your foreach loop with the following and let me know :
$id1 = $_POST['id'];
$test_result1 = $_POST['test_result'];
foreach( $id1 as $key => $value ) {
$query = "UPDATE tbl_lab_item SET test_result='$test_result1[$key]' WHERE lab_item_id = '$key' ";
}
Problem is that you're telling PHP to build your input fields as arrays, but then treat it as a string later:
<td><input name="test_result[]" type="text" value="'.$row->test_result.'"></td>
^^--- array
$tresult = trim($_POST['test_result']);
^^^^^^^^^^^^^^^^^^^^^--- no array key, so you're assigning the entire array
$query = "UPDATE tbl_lab_item SET test_result='$tresult'
^^^^^^^^^^--- array in string context
trim() expects a string, but you pass in an array, so you get back a PHP NULL and a warning. That null then gets stuffed into your SQL statement, and there's your problem.

Categories