PHP Mysql Pasing as parameter TextArea more than 1 line - php

I am having an issue to pass a textarea to another page when contains more than one line.
I have 3 pages:
1.-_testInsertText.php = INSERT a new text in Database
2.-_testShowText.php = SELECT the texts from Database and redirect to Modify Page
3.-_testTextModify.php = UPDATE the text passed by _testShowText.php
My structure from my table from Database:
CREATE TABLE `tblTest`
(
`clmSerie` int (11) NOT NULL
,`clmTextArea` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
If I insert a text with two lines through _testInsertText.php I am able to display correctly through _testShowText.php
My problem is in redirecting (through href) those records with more than one line to _testTextModify.php page (For 1 line is working fine). It is not redirecting.
Could you please help me?
My code can be found below:
1.-_testInsertText.php
<?php
$txtEvolucion = '';
if(isset($_POST['Insert']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "INSERT INTO tblTest (clmTextArea) VALUES (?)";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "s", $txtEvolucion);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Inserted";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Insert TextArea</title>
</head>
<body>
<h1>Insert TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucion ?></textarea><br><br>
<button name="Insert" type="submit" id="contact-submit" data-submit="...Sending">Insert</button><br>
</fieldset>
</form>
</body>
</html>
2.-_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><a href="_testTextModify.php?descripcion=' . $descripcion .
'&serie=' . $serie .
'">Modify
</a></td>
<td align="left">' .$serie . '</td>
<td align="left">' .$descripcion . '</td>
';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>
3.-_testTextModify.php
<?php
$txtEvolucion = '';
$txtEvolucionOld = $_GET['descripcion'];
$idSerie = $_GET['serie'];
echo "<br>". "txtEvolucionOld={" . $txtEvolucionOld ."}";
if(isset($_POST['Modify']) && isset($_POST["txtEvolucion"]))
{
$txtEvolucion = $_POST["txtEvolucion"];
require_once('mysqli_connect.php');
echo "<br>". "txtEvolucion={" . $txtEvolucion ."}";
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmTextArea = ?
AND clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "sss", $txtEvolucion, $txtEvolucionOld, $idSerie);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo $affected_rows;
if($affected_rows == 1)
{
$txtEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<textarea id="txtEvolucion" name="txtEvolucion" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucion ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>

Thanks to comment by Sloan Thrasher, I modified _testTextModify.php and _testShowText.php
And now I am passing content to a hidden TextArea instead of a href to the modify page and it is working fine now when it comes with more than one line.
Thank you everyone :)
The new code below:
_testTextModify.php
<?php
if(isset($_POST['fromTestShowText']))
{
$txtEvolucionOld = $_POST['descripcion'];
$idSerie = $_POST['serie'];
}
if(isset($_POST['Modify']) && isset($_POST["txtEvolucionOld"]))
{
$txtEvolucionOld = $_POST["txtEvolucionOld"];
require_once('mysqli_connect.php');
$query = "UPDATE tblTest
SET clmTextArea = ?
WHERE clmSerie = ?
";
$stmt = mysqli_prepare($dbc, $query);
mysqli_stmt_bind_param($stmt, "ss", $_POST['txtEvolucionOld'], $_POST['idSerie']);
mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
echo "<br>". "affected_rows={" . $affected_rows ."}";
if($affected_rows == 1)
{
$txtEvolucionOld = $recibeSerieEvolucion = '';
echo "Modified";
mysqli_stmt_close($stmt);
}
else
{
ini_set('display_errors', 'On');
mysqli_stmt_close($stmt);
}
}
?>
<html>
<head>
<title>Modify TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Modify TextArea</h1>
<div id="divAgenda">
<form id="contact" action="" method="post">
<fieldset>
<input type="hidden" readonly id="idSerie" name="idSerie" size="2" type="text" maxlength="100" tabindex="3"
value="<?= $idSerie ?>"
><br>
<textarea id="txtEvolucionOld" name="txtEvolucionOld" tabindex="4" cols="90" rows="7"
value="<?= $txtEvolucionOld ?> "
><?= $txtEvolucionOld ?></textarea><br><br>
<button name="Modify" type="submit" id="contact-submit" data-submit="...Sending">Modify</button><br>
</fieldset>
</form>
</body>
</html>
_testShowText.php
<?php
$output = '';
require_once('mysqli_connect.php');
$query = mysqli_query($dbc,"SELECT clmSerie
,clmTextArea
FROM tblTest
"
) or die('Error to select!: {' . mysqli_error($dbc) . '}');
$count = mysqli_num_rows($query);
$output .= '<table border="1" align="left" cellspacing="5" cellpadding="8">
<tr><td align="left"><b>MODIFY </b></td>
<td align="left"><b>Id </b></td>
<td align="left"><b>Text Area </b></td>
</tr>';
while($row = mysqli_fetch_array($query))
{
$serie = $row['clmSerie'];
$descripcion = utf8_encode($row['clmTextArea']);
//$descripcion = nl2br($descripcion);
$output .= '<tr><td align="left"><form action="_testTextModify.php" method="post">
<button name = "fromTestShowText" type="image"
value="Submit">Modify
</button>
</td>
<td align="left">' .$serie . '</td>
<td align="left"><input hidden readonly id="serie" name="serie" type="text"
value="'. $serie . '"
>
<textarea id="descripcion" name="descripcion" cols="50" rows="6"
value = "'.$descripcion.'"
readonly>'. $descripcion .'</textarea>
</td>
</form>';
$output .= '</tr>';
}
?>
<html>
<head>
<title>Show TextArea</title>
</head>
<body>
<br>Show
<br>Insert
<h1>Show TextArea</h1>
<?php echo $output;?>
</body>
</html>

Related

PHP ODBC : Updating Form

I have a form and successfully connect them to the database.
Now I'm trying to update the data. Unfortunately, nothing happened when I click the submit button. I'm sure I miss something. Please help me, thank you.
config.php :
<?php
$conn=odbc_connect("dsn", "", "");
if (!$conn)
{
exit("Connection Failed : " . $conn);
}
?>
This is my code :
<?php
include "config.php";
ini_set('error_reporting', E_ALL);
error_reporting(-1);
$sql = odbc_exec( $conn, "SELECT
UserId,
UserName,
UserEmail
FROM DBA.tblUser
WHERE UserId='".$_GET['UserId']."'");
if(isset($_POST['submit']))
{
$UserId=$_POST["UserId"];
$UserName=$_POST["UserName"];
$UserEmail=$_POST["UserEmail"];
//UPDATE
$stmt = odbc_exec( $conn,
"UPDATE DBA.tableUsers SET
UserName = '$UserName',
UserEmail ='$UserEmail'
WHERE UserId=$UserId");
if ($stmt) {
echo "Update Success";
echo $UserName;
echo $UserEmail;
} else {
"Error : " . odbc_errormsg();
}
}
?>
Form :
<form class="form" method="post">
<tr>
<td class = "userid">User ID</td>
<td><?php echo $UserId = odbc_result($sql,'UserId'); ?></td>
</tr>
<tr>
<td class = "name">User Name<span class="required"> * </span></td>
<td><input type="text" name="UserName" value="<?php echo $UserName = odbc_result($sql,'UserName'); ?>"></td>
</tr>
<tr>
<td class = "email">Email<span class="required"> * </span></td>
<td><input type="text" name="UserEmail" value="<?php echo $UserEmail = odbc_result($sql,'UserEmail'); ?>"></td>
</tr>
<button name="submit" type="submit" value ="submit" >Update</button>
</form>
Replace
$UserName=$_POST["UserName"];
With
$UserName=$_POST["UserId"];
Why? Simply because in your form, you have name as UserId and not UserName
<input type="text" name="UserId" value="<?php echo $UserName = odbc_result($sql,'UserName'); ?>"></td>
I managed to get the answer with the same concept and variable.
config.php :
<?php
$conn=odbc_connect("dsn", "", "");
if ($conn) {
echo "Connected";
}
if (!$conn) {
exit("Connection Failed : " . $conn);
}
?>
code :
<?php
include "config.php";
$sql = odbc_exec( $conn, "SELECT
UserId,
UserName,
UserEmail
FROM DBA.tblUser
WHERE UserId='".$_GET['UserId']."'");
if(isset($_POST['submit'])) {
$UserName=$_POST["UserName"];
$UserEmail=$_POST["UserEmail"];
$stmt = odbc_exec($conn,
"UPDATE DBA.tblUser SET
UserName = '$UserName',
UserEmail ='$UserEmail'
WHERE UserId='".$_GET['UserId']."'");
if ($stmt) {
echo "Update Successfull";
echo $UserName;
echo $UserEmail;
}
else {
"Error : " . odbc_errormsg();
}
}
?>
html :
<!DOCTYPE html>
<html>
<head>
<title>Administration</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/userpage.css" media="screen"/>
<body>
<content>
<div class="user-form">
<div class="user-form-heading">Update User</div><br>
<form class="form" method="post">
<h><table class ="user">
<!-- .................................. Updatable ....................................... -->
<tr>
<td class = "name">User Name<span class="required"> * </span></td>
<td><input type="text" name="UserName" value="<?php echo $UserName = odbc_result($sql,'UserName'); ?>"></td>
</tr>
<tr>
<td class = "userid">User Id</td>
<td><?php echo $UserId = odbc_result($sql,'UserId'); ?></td>
</tr>
<tr>
<td class = "email">Email<span class="required"> * </span></td>
<td><input type="text" name="UserEmail" value="<?php echo $UserEmail = odbc_result($sql,'UserEmail'); ?>"></td>
</tr>
<tr>
<td>
<f><button name="submit" type="submit" value ="submit" >UPDATE</button></f>
</table>
</form>
</div>
</content>
</body>
</head>
</html>

Why are values from a url are not being passed to sticky form

I have created a php sticky form so data will not disappear when the submit button is clicked. A url link is being used to pass values to a form so they can be edited. However, the values from the url are not being passed into the form fields. Why are the values from the url not being passed into the form fields? Thank you so much for your time.
This is the code:
index.php
<?php
require_once('authorize.php');
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$data = mysqli_query($conn, $query);
echo '<table>';
echo '<tr><th>Name</th><th>Caption</th><th>Action</th></tr>';
while ($row = mysqli_fetch_array($data)) {
//link
echo '<td><a href="link.php?id=' . $row['id'] . '&image=' . $row['image1'] . '&name=' . $row['name'] .
'&caption=' . $row['caption'] .
'&video=' . $row['video'] . '">Edit </a>';
echo '</td></tr>';
}
echo '</table>';
echo "<br><br>";
mysqli_close($conn);
?>
</body>
</html>
sticky_form.php
<!DOCTYPE html>
<html>
<head>
<title>Edit Conent</title>
</head>
<body>
<h3>Edit Conent</h3>
<?php
require_once('appvars.php');
require_once('connectvars.php');
$vid="";
$vname="";
$vcaption="";
$vvideo="";
$id ="";
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
}
?>
<body>
<form action='' method="post" enctype="multipart/form-data" >
<table>
<tr>
<td>ID</td>
<td><input type="text" name="id" value="<?php echo $vid;?>"></td></tr>
<tr>
<td>Name</td>
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>"></td></tr>
<tr><td colspan="2">
<input type="submit" name="button_edit" value="Edit Content"></td></tr> </table>
</form>
<table border=1>
<tr><th>Name</th><th>Caption</th>
<th>Video</th> <th>Action</th></tr>
<?php
if (isset($_GET["id"])) {
$qry =mysqli_query($dbc, "Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)) {
echo '<tr><td>'.$row["name"].'</td>';
echo '<td>'.$row["caption"].'</td>';
echo '<td>'.$row["video"].'</td>';
echo '<td>Edit </td></tr>';
}
}
?>
</table>
</body>
</html>
Apparently you already have the values you need in stick_form.php:
else if(isset($_GET["id"])){
$qry = mysqli_query($dbc,"Select * From table1 Where id='".$_GET["id"]."'");
while($row=mysqli_fetch_array($qry,MYSQLI_ASSOC)){
$vid=$row["id"];
$vname=$row["name"];
$vcaption=$row["caption"];
$vvideo=$row["video"];
}
Try replacing this part of the code of stick_form.php:
<td><input type="text" class="bigger_textbox" name="name" value="<?php if (isset($_POST['name'])) {echo htmlentities($_POST['name']);}?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php if (isset($_POST['caption'])) {echo htmlentities($_POST['caption']);}?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php if (isset($_POST['video'])) {echo htmlentities($_POST['video']);}?>" </td></tr>
With:
<td><input type="text" class="bigger_textbox" name="name" value="<?php echo $vname; ?>"></td></tr>
<tr><td>Caption</td>
<td><input type="text" class="bigger_textbox" name="caption" value="<?php echo $vcaption; ?>"></td></tr>
<tr><td>Video</td>
<td><input type="text" class="bigger_textbox" name="video" value="<?php echo $vvideo; ?>"></td></tr>
Update
As you commented, after clicking the edit button, your form fields get empty. That's because you're not setting the correct variables in this part of your code:
if(isset($_POST["button_edit"])){
$id = $_POST["id"];
$name = $_POST['name'];
$caption = $_POST['caption'];
$video = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$name', caption='$caption', video='$video' Where id='$id'");
Change it to:
if(isset($_POST["button_edit"])){
$vid = $_POST["id"];
$vname = $_POST['name'];
$vcaption = $_POST['caption'];
$vvideo = $_POST['video'];
$qry = mysqli_query($dbc,"Update table1 Set name='$vname', caption='$vcaption', video='$vvideo' Where id='$vid'");
Hope it helps.

export mysql query to csv on button click

so i have a php code that shows a table from the mysql database
there is also a filter field which filters the table.
i need help exporting the results of the table to a csv file when the button "export data" is clicked.
how do i do that?
below is the code
<?php
error_reporting(0);
include("config.php");
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TAD Customer Search</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<style>
BODY, TD {
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
}
</style>
</head>
<body>
<form id="form1" name="form1" method="post" action="index.php">
<label>Search: </label>
<input type="text" name="string" id="string" size="20" value="<?php echo $_REQUEST["string"]; ?>" />
<label>Country: </label>
<select name="country">
<option value="">--</option>
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." GROUP BY country ORDER BY country";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<option value='".$row["country"]."'".($row["country"]==$_REQUEST["country"] ? " selected" : "").">".$row["country"]."</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Filter" />
</label>
Reset
</form>
<br />
<table style="text-align: left; width: 100%;" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="text-align: left;"><input type="submit" name="btnexportdata" value="Export Data" /></td>
<td style="text-align: right;">
<form method="post" action="input.php">
<input type="submit" value="Add" />
</form></td>
</tr>
</tbody>
</table>
<br />
<table width="100%" border="1" cellspacing="0" cellpadding="4">
<tr>
<td width="150" bgcolor="#CCCCCC"><strong>Account Number</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Company Name</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Country</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Email</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Phone Number</strong></td>
<td width="150" bgcolor="#CCCCCC"><strong>Brands</strong></td>
</tr>
<?php
if ($_REQUEST["string"]<>'') {
$search_string = " AND (cname LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR email LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR accnumber LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR pnumber LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR brands LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["country"]<>'') {
$search_country = " AND country='".mysql_real_escape_string($_REQUEST["country"])."'";
}
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_country;
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["accnumber"]; ?></td>
<td><?php echo $row["cname"]; ?></td>
<td><?php echo $row["country"]; ?></td>
<td><?php echo $row["email"]; ?></td>
<td><?php echo $row["pnumber"]; ?></td>
<td><?php echo $row["brands"]; ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="6">No results found.</td>
<?php
}
?>
</table>
</body>
</html>
here is the code you can try
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() . "<br>" . mysql_errno());
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() . "<br>" . mysql_errno());
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() . "<br>" . mysql_errno());
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end

trouble in submiting form in php

I'm doing a database project for university and I'm having a problem in here.
I receive from a previous page an id as $_POST['ids'] and in the form I send that same value in a hidden field so it can do a sort of a cicle.
But when I click the submit button I got a lot of errors on $service_info and no information is loaded on the page. I tried do var_dump() everything and I just can't find what is the problem in here.
<?php
//error_reporting();
require 'core/init.php';
require 'db/connect.php';
require 'functions/security.php';
?>
<html>
<head>
<title>Make a reservation</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/common.css">
</head>
<body>
<?php require 'parts/header.php'; ?>
<hr>
<?php
$query = "SELECT * FROM service WHERE id=" . $_POST['ids'];
if ($result = $db->query($query)) {
if ($result->num_rows) {
$service_info = $result->fetch_object();
$result->close();
}
}
$query = "SELECT name FROM tour WHERE id =" . $service_info->idtour;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$tour_name = $result->fetch_object();
$result->close();
}
}
$query = "SELECT SUM(nrseats) AS res_seats FROM reservation_service WHERE idservice =" . $service_info->id;
$nr_reservations_info = $db->query($query);
$nr_reservations = $nr_reservations_info->fetch_row();
$nr_reservations_info->close();
$count = $service_info->nrseats - $nr_reservations[0];
if($count === 0){
echo "<script>alert('There are no more places available for this tour. You are being redirected for the main page!')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
else{
$count = $service_info->nrseats;
}
?>
<form action="" method="POST">
<div class="registering">
<table>
<tbody>
<tr>
<td>
<label for="tname">Related tour</label>
</td>
<td>
<label for="splace"><br>Service name</label>
</td><p><br></p>
</tr>
<tr>
<td>
<input type="text" readonly="" name="tour" id="tour" required="" autofocus="" value="<?php echo $tour_name->name ?>">
</td>
<td>
<input type="text" readonly="" name="name" id="name" required="" value="<?php echo $service_info->name ?>">
</td>
</tr>
<tr>
<td>
<label for="sprice"><br>Price (€)</label>
</td>
<td>
<label for="sdescription"><br>Description</label>
</td>
</tr>
<tr>
<td>
<input type="number" name="price" id="price" readonly="" required="" value="<?php echo $service_info->price ?>">
</td>
<td>
<input type="text" name="description" id="description" required="" readonly="" value="<?php echo $service_info->description ?>">
</td>
</tr>
<tr>
<td>
<label for="sseats"><br>Seats left</label>
</td>
<td>
<label for="snreservations"><br>Number of reservations (people)</label>
</td>
</tr>
</tr>
<tr>
<td>
<input type="number" name="nrseats" id="nrseats" required="" value="<?php echo $count ?>" readonly="">
</td>
<td>
<input type="number" name="nrreservations" id="nrreservations" required="" value="1">
</td>
<td>
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
</td>
</tr>
</tr>
<tr>
<td colspan="2">
<label for="next"><br></label>
<input type="submit" value="Next">
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
<?php
if (!empty($_POST)) {
if (isset($_POST['name'], $_POST['ids'], $_POST['tour'], $_POST['price'], $_POST['description'], $_POST['nrseats'], $_POST['nrreservations'])) {
$_POST = array_map("trim", $_POST);
$name = $_POST['name'];
$tour = $_POST['tour'];
$price = $_POST['price'];
$description = $_POST['description'];
$nrseats = $_POST['nrseats'];
$nrreservations = $_POST['nrreservations'];
$ids = $_POST['ids'];
if (!empty($name) && !empty($ids) && !empty($tour) && !empty($price) && !empty($description) && !empty($nrseats) && !empty($nrreservations)) {
$query = "SELECT id FROM customer WHERE email='" . $_SESSION['user_email'] . "'";
if ($result = $db->query($query)) {
$id_user = $result->fetch_object();
$result->close();
}
$query = "SELECT id FROM reservation WHERE idtour={$service_info->idtour} AND idcustomer={$id_user->id}";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$id_reservation = $result->fetch_object();
$result->close();
}
}
$query = "SELECT * FROM reservation_service WHERE idservice=" . $service_info->id;
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_service_exists = $result->fetch_object();
if ($nrreservations < 1) {
echo "<script>alert('Your must make a reservation for, at least, one person!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($count - $nrreservations < 0) {
echo "<script>alert('You can not make the reservation because there are only " . $count . " seats available in this tour!')</script>";
echo "<script>window.open('new_reservation_service.php','_self')</script>";
} else if ($result->num_rows) {
$query = "SELECT * FROM reservation WHERE idcustomer= '" . $id_user->id . "' AND idtour= '" . $service_info->idtour . "'";
if ($result = $db->query($query)) {
if ($result->num_rows) {
$reservation_exists = $result->fetch_object();
$result->close();
if ($reservation_exists->idcustomer === $id_user->id) {
if ($reservation_exists->id === $reservation_service_exists->idreservation) {
echo "<script>alert('You already made a reservation for this service. Please see your reservation panel!')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
}else {
$query = "INSERT INTO reservation_service (idreservation, idservice, date, nrseats) VALUES (?, ?, NOW(), ?)";
$insert = $db->prepare($query);
$insert->bind_param('iii', $id_reservation->id, $service_info->id, $nrreservations);
$insert->execute();
echo "<script>alert('You successfully made a reservation! You are being redirected to your reservations page')</script>";
echo "<script>window.open('reservations.php','_self')</script>";
}
}
}
}
}
?>
change inside your form this input hidden you created:
<input type="hidden" name="ids" required="" value="<?php $service_info->id ?>">
to
<input type="hidden" name="ids" required="" value="<?php echo $service_info->id ?>">
If you don't echoing this value, $_POST['ids'] won't be get any value passed from form.

My PHP Form will not refresh properly

So when I hit submit on the form that is displayed, the page (if working properly) should refresh, and the ELSE statement should be displayed instead, but I have 2 problems
The else statement is not displayed until I manually refresh the page
The Pub Score is not updated until the page is manually refreshed either, I think my code placement might be what's causing it, but I tried to put my form as far down as I could, I'm out of ideas, any help would be great thanks.
<?php
require_once('header.php');
require_once('connectdb.php');
require_once('sessioncheck.php');
if (isset($_SESSION['user_id'])) {
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_DATA);
$user_name = mysqli_real_escape_string($dbc, trim($_GET['username']));
$query = "SELECT * FROM blah WHERE username = '$user_name'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
if (mysqli_num_rows($data) != 0) {
if ($row['havemic'] == 1) {
$micstatus = "Yes";
} else {
$micstatus = "No";
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title><?php echo $user_name . ' profile' ?></title>
</head>
<body>
<?php
$commenduser = $user_name;
$query = "SELECT * FROM blah where commenduser = '$commenduser'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
$lowerusername = strtolower($username);
$loweruser_name = strtolower($user_name);
if (mysqli_num_rows($data) == 0) {
if (isset($_POST['submit'])) {
$commendplayer = mysqli_real_escape_string($dbc, trim($_POST['commendplayer']));
$commend = mysqli_real_escape_string($dbc, trim($_POST['commend']));
$comment = mysqli_real_escape_string($dbc, trim($_POST['comment']));
if (empty($comment)) {
echo '<p class="error">Please fillout a comment before submitting</p>';
} else {
$query = "INSERT INTO commend (commendby, commenduser, comment) VALUES ('$username', '$user_name', '$comment')";
mysqli_query($dbc, $query);
if ($commend == true) {
$query = "UPDATE blah SET points=points+1 WHERE username='$user_name'";
mysqli_query($dbc, $query);
echo '<p class="success">Your commendation has been submitted with + 1 account points.</p>';
} else {
echo '<p class="success">Your commendation has been submitted with no affect on the users account points.</p>';
}
}
}
} else {
echo '<p class="success">You have already submitted a commendation for this player.</p>';
}
?>
<div id="accsettings">
<table cellpadding="5">
<tr><td><label for="username" class="reglabel">Username: </label></td>
<td><label for="username" class="reglabel"><?php echo $row['username']; ?></label></td></tr>
<tr><td><label class="reglabel">Pub Score: </label></td><td><label class="reglabel">
/*This value 'points' should be updated to the new value after form submit */
/*As well the ELSE statement near the bottom should be displayed*/
<?php echo $row['points'] ?></label></td></tr>
<tr><td><label for="steamname" class="reglabel">Steam Name: </label></td>
<td><label for="steamname" id="acclink"><?php echo '' . $row['steamname'] . ''; ?></label>
<tr><td><label for="favchar" class="reglabel">Prefered Hero: </label></td>
<td><label for="favchar" class="reglabel"><?php echo $row['favchar']; ?></label></td></tr>
<tr><td><label for="language" class="reglabel">Spoken Language: </label></td>
<td><label for="language" class="reglabel"><?php echo $row['language']; ?></label></td></tr>
<tr><td><label for="playernote" class="reglabel">Player Note: </label></td>
<td><label for="playernote" class="reglabel"><?php echo $row['note']; ?></label></td></tr>
<tr><td><label for="micstatus" class="reglabel">Has a Mic and VO-IP?</label></td>
<td><label for="micstatus" class="reglabel"><?php echo $micstatus; ?></label></td></tr>
<tr><td colspan="2">Players Comments</td></tr>
<?php
if ($row['commendby'] != $username && $lowerusername != $loweruser_name) {
?>
<tr><td><br></td></tr>
<tr><td colspan="2"><p class="success">Player Commendations/Comments</p></td></tr>
<tr><td><br></td></tr>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] . '?username=' . $user_name; ?>">
<tr><td><label for="comment">Leave a comment</label></td>
<td><input type="text" name="comment" class="regtext" /></td></td>
<tr><td colspan="2"><label for="commend" class="right">Commend Player?</label><input type="checkbox" class="right" name="commend" value="yes" /></td></tr>
<tr><td colspan="2"><input id ="submit" type="submit" class="button1" name="submit" value="Submit" /></td></tr>
</form>
<?php
} else {
/*This is what should be being displayed after the form is submitted. But it is not.*/
$query = "SELECT * FROM blah where commenduser = '$commenduser'";
$data = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($data)) {
echo '<tr><td><br></td></tr>';
echo '<tr><td><br></td></tr>';
echo '<tr><td><label class="reglabel" for="commendedbyy">Comment From: ' . $row['commendby'] . '</label></td>';
echo '<td><label class="reglabel">' . $row['comment'];
echo '<input type="hidden" name="submit" />';
echo '</form>';
}
}
?>
</table>
<?php
} else {
echo '<p class="error">' . $user_name . ' is not a registered account.</p>';
}
}
else {
echo '<p class="error">You must Log In to view this profile.</p>';
}
?>
</div>
</body>
</html>
<?php
require_once('footer.php');
?>
The $row is first grabbed from the database and then the database is updated.
You can do one of three things, the last being the simplest:
You can refactor the code to change the order
Reload the data using another query after the update
Once you update the points then update the array (i.e. do $row['points'] = $row['points'] + 1;)

Categories