Hidden value not posted - php

I have some Problems with the following code.
The hidden field is not posted to the next page.
I have tried to put it next to the option field, but that creates some different problems like duplicating the dropdownmenue.
can anyone help me please?
<?php
$dbhost = 'localhost';
$dbuser = '-----';
$dbpass = '-----';
$db = '-----';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
$query = "SELECT * FROM Eintraege"; $result = mysql_query($query);
?>
<form action="deletescript.php" method="post">
<select name="loeschen">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ID'];?>"><?php echo $line['Titel'];?></option>
<?php
}
?>
</select>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="hidden" name="titel" value="<?php echo $line['Titel'];?>" />
<?php
}
?>
Vorname <br /><input type="text" name="name" value="" class="text" /><br /><br />
Name <br /><input type="text" name="vorname" value="" class="text" /><br /><br />
Email <br /><input type="text" name="email" value="" class="text" /><br /><br />
<input type="submit" name="submit" />
</form>

You should at least use mysqli, making sure you have the connection on a secure page like:
// connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You have a couple of other problems too.
1) Since mysql_fetch_array() always returns the next row of results, when mysql_fetch_array() is called again in your second while loop, $line is falsey, because there are no more rows to fetch, so the loop does not run. You could reset($line) if you're using fetch like that, but I recommend otherwise.
2) You cannot use the same HTML name attribute twice, unless you add [] to the end of it. Then you can access it as an Array in PHP.
// otherpage.php
<?php
include 'connect.php'; $db = db(); $opts = $hdns = '';
if($q = $db->query('SELECT * FROM Eintraege')){
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$t = $r->Titel;
$opts .= "<option value='$t'>$t</option>";
$hdns .= "<input name='titel[]' type='hidden' value='$t' />";
}
// now you can echo $opts and $hdns where you want
}
else{
$errors[] = 'No result rows were found';
}
$q->free();
}
else{
$errors[] = 'database connection failure';
}
$db->close(); if(isset($errors))die(implode(' & ', $errors));
?>
To get the titel named inputs on the page you are submitting to, it's like:
<?php
if(isset($_POST['titel'])){
// get each one
foreach($_POST['titel'] as $t){
// $t is each one
}
}
?>
Note that getting data to put into hidden inputs then sending it back to the server is generally pointless, since you have access to that information anyways. You'll want to learn AJAX if you want something to go to the database based on Client input.

Related

Warning: Illegal string offset error

I'm trying to create a simple search engine in php, in which if the user enters a keyword they can search by event name or location. Then the results to be displayed in date order. Most of the has been taken from another site, but I am trying to convert it.
Can someone explain the error below to a newbie, in simple terms and how to correct it?
/home/ubuntu/workspace/test/test.php:49: array(5) { 'eventID' => string(1) "1" 'eventName' => string(8) "Exciting" 'eventLocation' => string(7) "Stadium" 'commencing' => string(10) "2017-04-01" 'expires' => string(10) "2017-04-30" } Warning: Illegal string offset 'eventName' in /home/ubuntu/workspace/test/test.php on line 50 Call Stack: 0.0003 238624 1. {main}() /home/ubuntu/workspace/test/test.php:0 1
<?php
session_start();
//include files
include 'header/header.php';
include 'nav/navigation.php';
include 'init.php';
$expires = strtotime($_POST["expires"]);
$expires = date('Y-m-d', $expires);
$events = "";
$find = $_POST['find'];
$field = $_POST['field'];
$searching = true;
if(isset($_POST["submit"])) {
if(!empty($_POST["events"])) {
$searching = false;
}
//This is only displayed if the user submitted the form
if($searching == true)
{
echo "<h2>Results</h2><p>";
//If the user did not enter a search term, they receive an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to the database
//$result = mysqli_query($connection,$query) or exit ("Error in query:
$query. ".mysqli_error($connection));
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$mysqli = new mysqli('localhost', 'root', '', 'c3470438');
$query = "SELECT * FROM events WHERE upper(eventLocation)
LIKE'%STADIUM%'";
$result = $mysqli->query($query);
//Temporarily echo $query for debugging purposes
//echo "$query";
//exit;
//And display the results
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<br>";
foreach($row as $item) {
var_dump($row);
echo $item['eventName'];
exit();
}
exit;
//This counts the number or results. If there aren't any, it gives an
explanation
$anymatches=mysql_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br>
<br>";
}
//And reminds the user what they searched for
echo "<b>Searched For:</b> " .$find;
}
}
?>
<fieldset>
<legend><h2>Events</h2></legend>
<form name="search" method="post" action="<?=$PHP_SELF?>">
<tr> <th> <td>
<fieldset>
<legend>Find all events</legend>
<input type="radio" name="events" <?php if (isset($events) &&
$events=="all") echo "checked";?>value="all"> Display all events
</fieldset>
<fieldset>
<legend>Find events by date</legend>
<input type="date" name="date" min="<?php echo date("Y-m-d");?>"
max="2025-01-01" value="<?php echo date("Y-m-d");?>">
</fieldset>
<fieldset>
<legend>Find events by keywords</legend>
<input type="hidden" placeholder='Search by keyword'name="searching"
value="yes" />
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="eventName">Event Name</option>
<Option VALUE="eventLocation">Event Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="submit" />
</form>
</fieldset>
<button name="submit" value="submit" type="submit" class="button
expanded">Submit </button>
<button type="reset" value="Clear"class="button expanded">
Clear</button>
</fieldset>
</select> </td></tr>
<?php
//include files
include 'footer/footer.php';
?>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
</script>
</body>
Well $result->fetch_array(MYSQLI_ASSOC) returns a single row, but you are using it as if it returns all rows. So your foreach is iterating each field in the row, not each row and therefore you're trying to access an array key of a string.
Use a while like so:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['eventName'];
}
Also, you're using mysql_num_rows which is not part of mysqli. Instead use $result->num_rows.

How to use forms to update SQL

I'm trying to make a form that uses a drop down, radio buttons, text field, textarea, and a hidden value(the time) then takes that information from that form and updates SQL database.
My form is below and it all loads correctly but I'm having issues updating the values and trying to figure out how to make the radio buttons and dropdowns to work since I can't make the value php code and need to pass the value. Everything I'm finding on the web is how to do text fields where the user types something.
When I select update it just submits the data but nothing changes. On my update.php I have a sanitize function at the very end and am unsure how to pass the variables in. Do I create an array named $var and input all my variables into it or pass each variable at a time?
I've been searching the web for HOW TO's and am currently reading two books but they don't go into enough detail so thanks for any assistance.
control.php
<?php
session_start();
if( !isset($_SESSION['myusername']) ){ header("Location: login.php"); }
?>
<?php
require("../../system/templates/includes/constants.php");
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(!$connection) { die("Database connection failed: " .mysql_error()); }
$db_select = mysql_select_db(DB_NAME,$connection);
if(!$db_select) { die("Database selection failed: " . mysql_error()); }
?>
<form method="post" action="update.php">
<select name="name" required="true" value="<?php echo $row['name']; ?>">
<?php
$query="SELECT id, name FROM modules";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)) {
echo "<option value=\"" . $row['id'] . "\">" . $row['name'] . "</option>";
}
?>
</select>
<br />
Select Status:
Red <input type="radio" value="red" name="status" />
Yellow <input type="radio" value="yellow" name="status" />
Green <input type="radio" checked="checked" value="green" name="status" />
<br />
Reason:
<br />
<select name="reason" required="true">
<option value="0" selected="selected" value="">Select Reason</option>
<option value="ONLINE">Online</option>
<option value="MAINTENANCE">Maintenance</option>
<option value="ERROR">Error</option>
<option value="OFFLINE">Offline</option>
<option value="">No Reason</option>
</select>
<br />
ETA:
<br />
<input type="text" name="eta" value="<?php echo $row['eta']; ?>" maxlength="8" />
<br />
Description:
<br />
<textarea rows="5" cols="30" name="explanation" wrap="hard" required="true" maxlength="320" value="<?php echo $row['description']; ?>" /></textarea>
<br />
<div align="right">
<input name="update" type="submit" value="Update"/>
<input type="hidden" name="last_updated" value="<?php $mysqldate = date ('H:i'); $phpdate = strtotime ( $mysqldate );?> />
</form>
update.php
<?php
print_r(_POST);
if(isset($POST['update']))
{
$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS);
if(! $connection)
{
die('Could not connect: ' .mysql_error());
}
$name = $POST['name'];
$status = $POST['status'];
$reason = $POST['reason'];
$eta = $POST['eta'];
$description = $POST['description'];
$last_updated = $POST['last_updated'];
$updated_by = $POST['updated_by'];
$sql = "UPDATE module SET status = $status , reason = $reason , eta = $eta , description = $description , last_updated = $last_updated , updated_by = $updated_by WHERE name = $name";
mysql_select_db('status');
$retval = mysql_query ( $sql, $connection);
if (!retval)
{
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully";
mysql_close($connection);
} else {
// not sure what to do here
}
function sanitizeString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
function sanitizeMySQL($var)
{
$var = mysql_real_escape_string($var);
$var = satnizeString($var);
return $var;
}
header("Location: control.php");
?>
As always I greatly appreciate any assistance anyone can offer. I'm still in the very early stages of learning this and this website and community has helped me more than any book/tutorial I've read so far.
Your SQL statement needs quotation marks for each parameter.
$sql = "UPDATE module SET status = '$status' , reason = '$reason' , eta = '$eta' , description = '$description' , last_updated = '$last_updated' , updated_by = '$updated_by' WHERE name = '$name' ";
As for the sanitizeString() function, it only takes in one string at a time. Maybe something like the one below may be simple and clean:
$params = array($name, $status, $reason); // put all your params in here
foreach ($params as &$p) { // the '&' before $p is essential, so do not forget it
$p = sanitizeString($p);
}
Hope it helps.

Checkboxes and text doesn't want to show the value

<!DOCTYPE html>
<html>
<head>
<title>Talenquiz2</title>
</head>
<body>
<?php
if (isset($_GET["controleer"]))
{
$vraag = $_GET["vraag"];
$juistantwoord = $_GET["juistantwoord"];
$foutantwoord1 = $_GET["foutantwoord1"];
$foutantwoord2 = $_GET["foutantwoord2"];
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen");
while($row = mysql_fetch_array($result))
{
if ($row['vraag'] == $vraag)
{
if ($row['juistantwoord'] == $juistantwoord)
{
echo "Juist!<br />";
}
else
{
echo "Fout!<br />";
}
}
}
mysql_close($con);
echo "\n<hr />\n";
}
$aantalvragen=1;
$con = mysql_connect("localhost","root","");
mysql_select_db("dbproject", $con);
$result = mysql_query("SELECT * FROM tblquizvragen WHERE id='". $aantalvragen . "';");
$row = mysql_fetch_array($result);
The program is a quiz, it asks 5 questions with 3 chckbox 1 is corect and 2 are incorrect.
for ($aantalvragen=1; $aantalvragen<=5; $aantalvragen++)
{
$row = mysql_fetch_array($result);
}
her i lin
$vraag = $row['vraag'];
$juistantwoord = $row['juistantwoord'];
$foutantwoord1 = $row['foutantwoord1'];
$foutantwoord2 = $row['foutantwoord2'];
mysql_close($con);
?>
<form>
It doensn't show the values of the rows in my browser it shows only an open text and an open checkbox.
<input type="text" name="vraag" value="<?php echo $vraag; ?>" /><br />
<input type="checkbox" name="juistantwoord" value="<?php echo $juistantwoord; ?>" /><br />
<input type="checkbox" name="foutantwoord1" value="<?php echo $foutantwoord1; ?>" /><br />
<input type="checkbox" name="foutantwoord2" value="<?php echo $foutantwoord2; ?>" /><br />
<input type="submit" value="Controleer je antwoord" name="controleer" />
</form>
</body>
</html>
Your code is incorrect for fetching from the db
for(...) {
$row = mysql_fetch_array(...);
}
You simply loop over 5 lines of results, regardless of how many there may be, and assign the row array to $row... but do so for EVERY row without ever using them. So you end up trashing the first n-1 rows and come out of the loop with only row n saved.
If you're wrong with how many rows of data you're expecting, your 5-item loop may have only a 4-item result set to deal with, and the final row $row1 value will be the boolean FALSE that msyql_fetch returns when there's no more data.
Try something like this instead:
while($row = mysql_fetch_assoc($result)) {
echo ..... your stuff here ...
}
Far more reliable, doesn't depend on there being a known number of rows available, and will not output anything if there's no data at all.

updating a record in database not working

again I'm trying to study php mysql and it seems that I tried everything thing to figure the problem out.. but it seems as a beginner codes in the internet are not helping.. I really can't update the records in the database.
<html>
<body>
<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("dbtry",$db);
$id = isset($_GET['id']) ? $_GET['id'] : null;
$submit = isset($_POST['submit']);
if ($id) {
if ($submit) {
$result = mysql_query("select * from employees where id = " . mysql_real_escape_string($_GET['id']) );
$row = mysql_num_rows($result);
if ($myrow != 0) {
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
}
echo "Thank you! Information updated.\n";
} else {
// query the DB
$result = mysql_query("SELECT * FROM `employees` WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="first" value="<?php echo $myrow["firstname"] ?>"><br>
Last name:<input type="Text" name="last" value="<?php echo $myrow["lastname"] ?>"><br>
Address:<input type="Text" name="address" value="<?php echo $myrow["address"]
?>"><br>
Position:<input type="Text" name="position" value="<?php echo $myrow["position"]
?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
} else {
// display list of employees
$result = mysql_query("SELECT * FROM employees",$db);
while ($myrow = mysql_fetch_array($result)) {
printf("%s %s<br>\n", $_SERVER['PHP_SELF'], $myrow["id"],
$myrow["firstname"], $myrow["lastname"]);
}
}
?>
</body>
</html>
There are two things potentially causing you a problem: firstly, the values you are trying to set are variables which have not been defined. I'm assuming the begginers code you found assumed you had register globals enabled, you really don't want to do this!
The second problem, is that if you do have register globals enabled, the data isn't being sanitized, so a quotation mark could send the update awry.
Try this instead:
$first = mysql_real_escape_string( $_POST['first'] );
$last = mysql_real_escape_string( $_POST['last'] );
$address= mysql_real_escape_string( $_POST['address'] );
$position = mysql_real_escape_string( $_POST['position'] );
mysql_query ("UPDATE employees SET firstname='$first',lastname='$last',address='$address',position='$position' WHERE id = '$id'");
This should at least get you up and running. I'd strongly advise that you use either the MySQLi library, or PHP PDO, and think about using prepared statements for added security.
mysql_query("UPDATE `employees` SET `firstname`='".$first."', `lastname`='".$last."',
`address`='".$address."', `position`='".$position."' WHERE `id` = '".$id".' ; ", $db) or
die(mysql_error());
I think the problem may lie in your connection to the database. The third parameter of the mysql_connect function is a password. Therefore this:
$db = mysql_connect("localhost", "root");
should be:
$db = mysql_connect("localhost", "root", "yourPassword");
It would also help a lot if you posted what type of error you are getting.
You need to differentiate post and get. Follow the working example below. It will sort you out :D
<html>
<body>
<?php
$db = mysql_connect("localhost", "root","");
mysql_select_db("test",$db);
if($_SERVER['REQUEST_METHOD']=='POST')
{
//SUBMIT FORM
$id=isset($_POST['id'])?$_POST['id']:0;
if ($id) {
$result = mysql_query("select * from parameter where id = " . mysql_real_escape_string($id) );
$rows = mysql_num_rows($result);
if ($rows != 0) {
mysql_query ("UPDATE parameter SET name='".$_POST['name']."',value='".$_POST['value']."' WHERE id = '".$id."'");
echo "Thank you! Information updated.\n";
}
}
}
if($_SERVER['REQUEST_METHOD']=='GET')
{
//SELECT WHERE ID=GER VAR AND DISPLAY
$id = isset($_GET['id']) ? $_GET['id'] :0;//
if ($id) {
// query the DB
$result = mysql_query("SELECT * FROM parameter WHERE `id` = " . mysql_real_escape_string($_GET['id']), $db);
$myrow = mysql_fetch_array($result);
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']?>">
<input type=hidden name="id" value="<?php echo $myrow["id"] ?>">
First name:<input type="Text" name="name" value="<?php echo $myrow["name"] ?>"><br>
Last name:<input type="Text" name="value" value="<?php echo $myrow["value"] ?>"><br>
<input type="Submit" name="submit" value="Enter information">
</form>
<?php
}
else {
// display list of employees
$result = mysql_query("SELECT * FROM parameter",$db);
while ($myrow = mysql_fetch_array($result)) {
echo "<a href='".$_SERVER['PHP_SELF']."?id=".$myrow['id']."'>".$myrow['name'].": ".$myrow['value']."</a><br>";
}
}
}
?>
</body>
</html>
Usually when I run into this problem, it's because auto commit is off and I forgot to tell the connection explicitly to commit.
EDIT: Have you tried this: How can I implement commit/rollback for MySQL in PHP?? Depending on your settings, InnoDB can be set to auto commit off, which means you need to tell MySQL explicitly to commit updates after your done.

PHP IF ELSE - If seems to be ignored?

i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...

Categories