How to assign text input to php valuables without submitting - php

Hi I am new to web developing. I am having a submit php page which is submitting datas from previous form page and also showing submit confirming info. But now I am going to make it asking users to enter 2 more things ( name and room number) before submitting to SQL, so... information from previous form and name, room number will be insert to SQL all together. I want to handle this submission within one same page, but for the new added 2 datas (name & room number) I don't want to do one separate submit() since I don't want the page refreshing,
How can I do it? How can I apply value from an input tag(Cname) to $Cname ? without refreshing the page ? Here is my code:
...
<head>
<?php
$T1comment1 = $_POST['T1comment1'];//these are from previous form
$T1comment2 = $_POST['T1comment2'];//these are from previous form
$T1comment3 = $_POST['T1comment3'];//these are from previous form
$T1comment4 = $_POST['T1comment4'];//these are from previous form
$item_1 = $_POST['item_1'];//these are from previous form
$item_2 = $_POST['item_2'];//these are from previous form
$item_3 = $_POST['item_3'];//these are from previous form
$item_4 = $_POST['item_4'];//these are from previous form
$Cname = $_POST['Cname'];
$CRnumber = $_POST['CRnumber'];
?>
</head>
<body>
<div>
<form method="POST" name="namdAndRm" id="namdAndRm" action="<?php echo $PHP_SELF;?>" >
<input type="text" id="Cname" name="Cname" value="your name here"></input>
<input type="text" id="CRnumber" name="CRnumber" value="room no."></input>
</form>
</div>
<div>
<div class="Back"></div>
<div class="submit" onclick="goSubmit();"></div>
</div>
<script type="text/javascript">
function goSubmit(){
<?php
$Cname = $_POST['Cname']; //is this the right way to do it?
$CRnumber = $_POST['CRnumber']; // I tested a lot, seams direct "=" is not working...
$SqlStatement = "INSERT INTO T3survey (T1item_1, T1comment1, T1item_2, T1comment2, T1item_3, T1comment3, T1item_4, T1comment4, Cname, CRnumber, day) VALUES ('$item_1', '$T1comment1', '$item_2', '$T1comment2', '$item_3', '$T1comment3', '$item_4', '$T1comment4', '$Cname', '$CRnumber', NOW())";
$result = mysql_query($SqlStatement,$connection);
if (!$result){ die("Error " . mysql_errno() . " : " . mysql_error());}
?>;
};
</script>
</body>
</html>

All you need to do is create a bunch of hidden fields in your form, like so:
<input type='hidden' name ='T1comment1' value='<?php $T1comment1;?>'>
<input type='hidden' name ='T1comment2' value='<?php $T1comment2;?>'>
<input type='hidden' name ='T1comment3' value='<?php $T1comment3;?>'>
<input type='hidden' name ='T1comment4' value='<?php $T1comment4;?>'>

Related

Process PHP form on hidden page, but stay on same page. No Ajax, pure php only (project)

I'm new to PHP, and I'm sure this is a common think to do, but 99% of the answers I have found to this involve AJAX, JQuery and/or JavaScript.
I am only allowed to use HTML/CSS and PHP in my project, so I need a working option that does not involve anything else.
I have the following setup:
index.php, this holds my form structure
insert.php, this sanitizes/validates and inserts form data into a database table
Leaving action as insert.php sends me to my insert.php page, which I want to keep private and for developer eyes only...no good.
form action=" " method="post"
// OR
form action="index.php" method="post">
Leaving action blank or as index.php keeps me on the same page, but...
I want to keep my form processing in a separate file (insert.php) and NOT on the same page, if at all possible.
Do I have any options for this that are not excessively complex in pure PHP?
Thanks for any advice.
(PS. If there's any blatant errors or poor form here, I'm all ears to constructive criticism)
Here's a snapshot of my insert.php file if its helpful. I can upload my form as well, but its very basic (just select a course, input first/last name, input student id).
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
Something like this might be what you want:
<?php
if (!empty($_POST)) {
require "insert.php";
}
?>
<html><head></head><body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
</body></html>
It's possible to submit the page to itself and check if the $_POST is empty or not. If it's empty show the form of the page if not insert the data into the database.
<?php if (!empty($_POST)):
// Clean the data coming from the MySQL tables
$course_clean = htmlentities($_POST['course_id']);
$stu_name_clean = htmlentities($_POST['first_last']);
$stu_id_clean = htmlentities($_POST['stu_id']);
// Escape user input coming from forms
$course = mysqli_real_escape_string($open, $_REQUEST['course_id']);
$stu_name = mysqli_real_escape_string($open, $_REQUEST['first_last']);
$stu_id = mysqli_real_escape_string($open, $_REQUEST['stu_id']);
// INSERT DATA
$insert = "INSERT IGNORE INTO enrolled (course_id, stu_id) VALUES ('$course', '$stu_id')";
if(mysqli_query($open, $insert)){
echo "Records added successfully to ENROLLED.";
} else{
echo "ERROR: Could not add records to ENROLLED. " . mysqli_error($open);
}
else: ?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<input type="text" name="course_id"><br/>
<input type="text" name="first_last"><br/>
<input type="text" name="stu_id"><br/>
<input type="submit">
</form>
<?php endif; ?>

Database Query failed error when inserting Row into Table

I am getting Database query failed error while trying to insert a new row into a table. This table (pages) has a column (subject_id) referencing another table (subjects). I am passing the value of the of the subject_id from the url and it is passed on the form correctly. All the values seem to be passed correctly on the form using php, but i get error while i try to insert the row. The form submits to itself.
select_all_pages_by_subject($sid) is a function that selects all rows (pages) from the current subject (passed from the url). It works fine for the position field.
I suspect this error is probably a MySQL syntax error somewhere in my code, but i just cant seem to figure it out yet. I appreciate some help. Thank you.
Here is my code:
<div class="body_content">
<?php
$sid = null;
if(isset($_GET["subject"])) {
$sid = $_GET["subject"];
}
?>
<form action="create_page.php" method="post">
Menu Name: <input type="text" name="menu" /> <br>
Position: <select name="position">
<?php
$new_page_query = select_all_pages_by_subject($sid);
$page_count = mysqli_num_rows($new_page_query);
for($count=1; $count<=($page_count + 1); $count++) {
echo "<option value=\"$count\">$count</option>";
}
?>
</select> <br>
Visible:<br>
No <input type="radio" name="visible" value="0" />
Yes <input type="radio" name="visible" value="1" /> <br>
Subject ID: <input type="text" name="subject_id" value="<?php echo $sid; ?>" /> <br>
Content: <br>
<textarea rows="5" cols="40" name="content"></textarea> <br>
<input type="submit" value="Create Page" name="submit" /> <br>
Cancel <br>
</form>
<?php
if(isset($_POST['submit'])) {
$menu_name = $_POST["menu"];
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$content = $_POST["content"];
$subject_id = (int) $_POST["$sid"];
$insert_query = "INSERT INTO pages (subject_id, menu_name, position,
visible, content) VALUES ({$subject_id},'{$menu_name}', {$position},
{$visible}, '{content}')";
$page_insert = mysqli_query($connection, $insert_query);
if($page_insert) {
$_SESSION["message"] = "Page created successfully";
redirect_to("admin.php");
} else {
$_SESSION["message"] = "Page creation failed";
redirect_to("create_page.php?subject=$sid");
}
}
?>
</div>
Edit: removed the WHERE statement
The problem is INSERT cannot have a WHERE after it.
$insert_query = "INSERT INTO pages (subject_id, menu_name, position, visible, content) VALUES ({$subject_id},'{$menu_name}', {$position}, {$visible}, '{content}')";
So after some troubleshooting, i decided to separate the form and form processing into 2 different pages, then i realized the problem, in the form action, i did not specify the subject id in the URL since i was passing the id from the URL:
<form action="create_page.php" method="post">
should be:
<form action="create_page.php?subject=<?php echo $sid; ?>" method="post">
Edit: I have also noticed that the "Database query failed" error was being called on the Position form field where i was making a database connection on the "pages" table to pull the number of rows. So when the insert statement failed due to the absence of subject id from the url, php did not process the page past the position form field, it called the error on the field and stopped execution. When insert query fails, parts of the form are displayed on the screen (only the menu name field and the position field with empty values). When i tried to view source code for errors, it requested the page be reloaded again (felt like an infinite loop running or something)

pass php variables from one form to be submitted to database in another

I have a pop up box which checks if the user is signed in or not. If he is, I'm echoing out a small form which the user will press a button and it will submit to the DB. The variables are displayed on the popup but when pressed submit, they do not pass to the submit php file.
$add_wish = "<form action='memWishList.php' method='post' id='memWishList'>
<h3>Add this item to your Wish List?</h3><br>
<input type='hidden' name='title' value='".$title."'>".$title."</input><br>
<input type='hidden' name='link' value='".$link."'></input><br>
<input type='submit' name='submit' value='Add'/><button id='cancel'>
Cancel</button>
</form>";
echo $add_wish;
I want to pass the values title and link to be submitted to the DB. Here's my memWishList.php file:
if (isset($_POST['submit'])){
//get member id
$title = mysqli_real_escape_string($_POST['title']);
$link = mysqli_real_escape_string($_POST['link']);
$mysql = "INSERT INTO wish_list (memNum, title, link, date) VALUES ('$memnum', \
'$title', '$link', now())";
$myquery = mysqli_query($mysqli_connect, $mysql);}
Doing it this way, I only get the member id and the date inserted, not the title and the link. What's the problem? The reason why I'm echoing out this form is there's an if/else statement for logged in users and non logged in. Would be much easier to do it in html but can't...
DB: memnum(varchar), title(longtext), link(longtext), date(date). I have other tables where long links and titles are inserted just fine as longtext. They're coming from rss feeds.
please check documentation: mysqli_real_escape_string function expect the string as 2nd parameter if you use a procedural approach. It could be i.e.:
$link = mysqli_real_escape_string($mysqli_connect, $_POST['link']);
You have some markup errors. Your hidden input tags should look like:
<input type='hidden' name='link' value="<?php echo $link ?>">
Update your HTML file to look like this and all of the values will be sent to the $_POST variable:
<form action='memWishList.php' method='post' id='memWishList'>
<h3>Add this item to your Wish List?</h3><br>
<input type='hidden' name='title' value="<?php echo $title ?>"><?php echo $title ?><br>
<input type='hidden' name='link' value="<?php echo $link ?>"><br>
<input type='submit' name='submit' value='Add'/><button id='cancel'>Cancel</button>
</form>

sql retrieve data from table and make them links

I am generating web pages from database. Now my question is:
I have 1000 records(names) in my database(MySql).
I have made a search box in a page and when i enter any name or a part of name that is in my DB all the name's should come up.
Eg-
SELECT * FROM table where name like '%$find%'
Now i want to show the selected names(fetched through the query) on the new page so that when i click on any of the name a new page should open up and all the data related to that selected name (present in the table belonging to the database)to be shown on that page with navigation buttons, what query should i use to perform it.
In short i want to make my page like Google search page.
My first page is like this
<html>
<body >
<h2>Search</h2>
<form name="search" method="post" action="second.php">
Search Name: <input type="text" name="find" id="find" />
<input type="submit" name="search" value="search" />
</form>
</body>
</html>
Second page is somewhat like this
<html>
<head>
<script>
function favBrowser()
{
var mylist=document.getElementById("opt");
document.getElementById("favorite").value=mylist.options[mylist.selectedIndex].text;
}
</script>
</head>
<body>
<form method="get">
<?php
$find = $_REQUEST['find'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("data", $con);
$result = mysql_query("SELECT * FROM table where name like '%$find%'");
$result_rows = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
// $names[] = $row['name'];
// echo $names[0];
// echo "$row[name]. $row[id] <a href='data.php?edit=$row[name]'>edit</a><br />";
$_name = $row['name'];
echo "Name : <input type='text' name='name' value='$_name' size='30'>";
echo "<br />";
}
}
mysql_close($con);
?>
<!--</select>
<input type ="submit" value="submit">
<p>Your selected name is: <input type="hidden" name="fun" id="favorite" size="30">
</p>
-->
</body>
</html>
Well, simplified, on the first page you'll have something like:
while($row = mysql_fetch_array($result))
{
$_name = $row['name'];
echo '<a href="second_page.php?name='.strip_tags($_name)'" target="_BLANK"'.'</a>';
}
and on the second page you have name, passed as URL parameter, on which you then do another database look up to get the contacts details and populate the various fields:
$_name = $GET['name'];
Please remember to add the required escapes or rather use PDO / mysqli
But the question is how will you make all the names as links and then fetch their result on next page .. right ?

Getting the wrong result in mysql?

Hello i have a html form in side php everything is working fine and i have just been showed how to do hidden fields from this website.
I have a submit button on each and every result letting the user pick what they want. When they press the submit button i want the info to be submitted and added to the database. But for some reason when the user click submit on item 1 it adds the last item into the database e.g item 6 ?? So there is 6 results and a submit button for each one so 6 buttons. When the user presses submit on number 1 item it submits number 6 for some resson.
<form method="post" action="buydo.php">
<label><br />
<br />
</label>
<p>
<?php
$sql = "SELECT * FROM sell
ORDER BY Pokemon_level ASC";
$res = mysql_query($sql) or die(mysql_error());
while ($v = mysql_fetch_array($res)) {
echo '
<div class="auction_box">
<img src="http://myrpg.net/new_rpg/'.$v['Pokemon_pic'].'" width="100" height="100"><br/>
£'.$v['price'].'<br/>
<label id="pokemonName'.$v['id'].'">'.$v['pokemon_name'].'</label><br/>
<label>Level '.$v['Pokemon_level'].'</level><br/>
<label>Exp '.$v['exp'].'</level><br/>
<label>Time Left:';
echo '</label>
<br/>
<input type="hidden" name="Name" value="'.$v['pokemon_name'].'">
<input type="hidden" name="level" value="'.$v['Pokemon_level'].'">
<input type="hidden" name="vid" value="'.$v['id'].'">
<input type="hidden" name="price" value="'.$v['price'].'">
<input type="hidden" name="exp" value="'.$v['exp'].'">
<input type="submit" id="'.$v['id'].'" class="buy_submit" value="Buy Now" /> </div>';
}
?>
</p>
<p> </p>
</form>
That is the select with the submit buttons for each result.
Then i insert the info they have chosen.
include 'config.php';
session_start() ;
$name = mysql_real_escape_string($_POST['Name']);
$Pokemon_level = mysql_real_escape_string($_POST['level']);
$idofpokemonsell = mysql_real_escape_string($_POST['vid']);
$price = mysql_real_escape_string($_POST['price']);
$exp = mysql_real_escape_string($_POST['exp']);
$sql = "SELECT * FROM `users` WHERE `username` = '" . $_SESSION['username'] . "'";
$result = mysql_query($sql) or die(mysql_error());
$values = mysql_fetch_array($result);
echo $values['money'] ;
if ( $values['money'] == $price ) {
echo "Give them the pokemon yay";
}
if ( $values['money'] > $price ) {
mysql_query("INSERT INTO `user_pokemon` (`pokemon`, `belongsto`, `exp`, `slot`, `level`) VALUES ('$name','" . $_SESSION['username'] . "','$exp','0','$Pokemon_level')") or die(mysql_error());
echo "Your money is over";
}
Like i say the insert only inserts item 6 no matter if u press item 1 - 5 it inserts 6 the level , exp, name everything of item 6
Since you display it all in one form, the latest values are overwriting the earlier ones. Try making each item its own form by moving your <form> and </form> tags inside your while loop
or try to track with jquery clicked button id and fill a hidden field with the clicked id
This is because your html is wrong. The values get overwritten
Basically you have to options:
render a form for each item
do it with a dropdown or radio buttons
With the second option you need to rewrite your code more, but it is more elegant, if you ask me. So what do you need to do.
Move the submit button out of the loop
Only generate code with the id and labels like this:
<option value="'.$v['id'].'"/>YOUR LABEL</option>
When the form is submitted, you have to retrieve the values corresponding to your the submitted id

Categories