HTML PHP (Why does not return value?) - php

I was actually trying to retrieve the input submit button value. But I don't know why it does not work. Can anyone help me?
When the user click the buttons, the button's value will be send to the next page.
<?php
include('connect.php');
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userauth";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
?>
<html>
<head>
<title>GAF APPS</title>
</head>
<body>
<form method="post" action="branch.php">
<input type="submit" name="submit" value="<?php echo $row["Company"]; ?>">
</form>
</body>
</html>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is where I was going to retrieve the value:
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>

You don't have an input named "action", therefore the isset() will never happen which is why you did not get an error for it
Having added an else condition for it, would have shown you that instead.

When debuging in PHP I tend the use the shotgun approach and output everything that could be remotely interesting and then narrow it down.
So when looking at parsing form variables use echo var_export($_GET, true) or vardump($_GET).
Not sure if GET or POST? Use _REQUEST which has both in 1 variable.
Use the HTML tag to make it more readable and htmlspecialchars() to convert characters that would normally be invisible because of your browser.
Using those will make it far easier to see what you are doing with your form.
So to answer the above question:
Look at the the mentioned request variables and determine by looking at the HTML and the code if the expected variables should be parsed and send by the browser when the submit button is pressed.
AND
See if the values actually received by PHP will have the expected outcome when handled.
Try to keep those 2 things separate, because what is in your HTML now does not mean it was there when you parsed the form. That's a bit of a bind when developing with PHP/HTML and forms, when you change the code and do not fully reload, but just press Submit on the form:
the code that will parse the current form will be changed, but the contents of the form parsed are the ones that where loaded in your browser and might be out dated.

Related

What's going on with my code?

I am using similar syntax in my blog. However, On my forum, nothing happens! This has been such an infuriating thing to tackle, as everything seems to be working exactly as my blog did. Here's my code I pass through and call the delete_post page
CHUNK FROM VIEWPOST.PHP
while($row = mysqli_fetch_array($result)){
echo '<tr>';
echo '<td class="postleft">';
echo date('F j, Y, g:i a', strtotime($row['forumpost_Date'])) . "<br>" .$row['user_Name']. "<br>" .$row['forumpost_ID'];
echo '</td>';
echo '<td class="postright">';
echo $row['forumpost_Text'];
echo '</td>';
if(isset ($_SESSION['loggedin']) && ($_SESSION['user_AuthLvl']) == 1){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
else if(isset ($_SESSION['loggedin']) && ($_SESSION['user_ID']) == $row['forumpost_Author']){
echo '<td class="postright">';
echo '<a class= "btn btm-default" href="#">Edit</a>';
echo '<a class= "btn btm-default" href="delete_post.php?forumpost_ID='.$row['forumpost_ID'].'">Delete</a>';
echo '</td>';}
echo '</tr>';
}echo '</table>';
DELETE POST FUNCTION
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID']);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
Now it is showing the ID's as intended, it just simply does not delete the post. It's such a simple Query, I don't know where my syntax is not matching up!
EDIT FOR DBCONNECT.PHP
<?php
/*---------------------------------------
DATABASE CONNECT PAGE
A simple connection to my database to utilize
for all of my pages!
----------------------------------------*/
$host = 'localhost';
$user = 'ad60';
$password = '4166346';
$dbname = 'ad60';
$connectDB = mysqli_connect($host, $user, $password, $dbname);
if (!$connectDB){
die('ERROR: CAN NOT CONNECT TO THE DATABASE!!!: '. mysqli_error($connectDB));
}
mysqli_select_db($connectDB,"ad60") or die("Unable to select database: ".mysqli_error($connectDB));
?>
Ok, I saw this and I would like to suggest the following:
In general
When you reuse code and copy paste it like you have done there is always the danger that you forget to edit parts that should be changed to make the code work within the new context. You should actually not use code like this.
Also you have hard coded configuration in your code. You should move up all the configuration to one central place. Never have hard coded values inside your functional code.
Learn more about this in general by reading up about code smell, programming patterns and mvc.
To find the problem
Now to fix your problem lets analyse your code starting with delete_post.php
First check if we actually end up inside delete_post.php. Just place an echo "hello world bladiebla" in top of the file and then exit. This looks stupid but since I can't see in your code if the paths match up check this please.
Now we have to make sure the required references are included properly. You start with the include functionality of php. This works of course, but when inside dbconnect.php something goes wrong while parsing your script it will continue to run. Using require would fix this. And to prevent files from loading twice you can use require_once. Check if you actually have included the dbconnect.php. You can do this by checking if the variables inside dbconnect.php exist.
Now we know we have access to the database confirm that delete_post.php received the forumpost_ID parameter. Just do print_r($_GET) and exit. Check if the field is set and if the value is set. Also check if the value is actually the correct value.
When above is all good we can go on. In your code you check if the forumpost_ID is set, but you do not check if the forumpost_ID has an actual value. In the above step we've validated this but still. Validate if your if
statement actually functions by echoing yes and no. Then test your url with different inputs.
Now we know if the code actually gets executed with all the resources that are required. You have a dedicated file that is meant to delete something. There is no need to use a function because this creates a new context and makes it necessary to make a call and check if the function context has access to all the variables you use in the upper context. In your case I would drop the function and just put the code directly within the else statement.
Then check the following:
Did you connect to the right database
Is the query correct (echo it)
Checkout the result of mysqli_query
Note! It was a while ago since I programmed with php so I assume noting from the codes behavior. This is always handy. You could check the php versions on your server for this could also be the problem. In the long run try to learn and use MVC. You can also use frameworks like codeigniter which already implemented the MVC design pattern.
You have to declare $connectDB as global in function.
function delete($table, $forumpost_ID){
global $connectDB;
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
See the reference about variable scope here:
http://php.net/manual/en/language.variables.scope.php
please try to use below solution.
<?php
include ('header.php');
include ('dbconnect.php');
//A simple if statement page which takes the person back to the homepage
//via the header statement after a post is deleted. Kill the connection after.
if(!isset($_GET['forumpost_ID'])){
header('Location: index.php');
die();
}else{
delete('hw7_forumpost', $_GET['forumpost_ID'], $connectDB);
header('Location: index.php');
die();
}
/********************************************
delete function
**********************************************/
function delete($table, $forumpost_ID, $connectDB){
$table = mysqli_real_escape_string($connectDB, $table);
$forumpost_ID = (int)$forumpost_ID;
$sql_query = "DELETE FROM ".$table." WHERE id = ".$forumpost_ID;
$result = mysqli_query($connectDB, $sql_query);
}
?>
I wish this solution work for you best of luck!

Sending data to database only after submit has been clicked on a form that posts to same page

I have a form that posts to the same page because I need the values to display below after submit has been clicked, which it does. The problem is that as soon as the page is loaded, the php runs and sends the data to the database instantly, so it sends an empty value to the database since the user has not submitted anything.
$servername = "localhost";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO my_table (firstname)
VALUES (:firstname)");
$stmt->bindParam(':firstname', $firstname);
// insert a row
$firstname = $name;
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="post" id="nick-form" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
?>
I would like the $name variable to only get sent when the user hits submit, if possible.
"I would like the $name variable to only get sent when the user hits submit, if possible."
Use a conditional isset() with your submit button.
<?php
if(isset($_POST['submit']))
{
// code to execute
}
Sidenote: You could/should also add an !empty() on your inputs also, which is highly recommended in order to prevent empty submissions.
You could also implement a header upon successful submission to redirect to another page:
header('Location: http://www.example.com/');
exit; // avoid further execution of code, if any resides below that
http://php.net/manual/en/function.header.php
Just make sure you're not outputting before header if you plan on using it.
Here's an article on Stack about this:
How to fix "Headers already sent" error in PHP
There is also a good article on how to prevent multiple submits using sessions and tokens:
http://www.phpro.org/tutorials/Preventing-Multiple-Submits.html
Something I have used in the past with success which could be useful.
What you have is a possible checking clause with an if statement using
if (count($_POST) > 0) {
//code runs if POST is submitted data
if (!empty($_POST['name'])){
///process the name form field value
}
}
Which would solve your issue, BUT when the page is refreshed by the user, the refreshed page will also resubmit the POSTED data , this is why on database activity pages it is HIGHLY advisable to send the data to another page, and then once the data is saved, return the browser to the original page, so refreshing the original page does not resubmit the POSTED data
To illustrate further, make another PHP file called "save.php" and everything in the PHP tags ABOVE the <form> element, put in the save.php file, then set the form to goto save.php and at the bottom of the save.php set a header("location:formpage.php");die(); to return to the form.
You will still need a database call on the form page to display the desired output. But this will prevent resubmitting of data upon page refresh
You can use if :
if(isset($_POST['name']) && $_POST['name'] != null) {
// Your code
}
You should also check $_POST['submit'].

Adding to a value in a table on the press of a button on a webpage?

I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.

POST doesn't work fine

Well I have a problem with my code:
if ($_POST) {
//send confirmation email (or insert into database, etc...)
if(isset($_POST['del'])) {
$Link = $_POST['del_link'];
$query = "UPDATE comentarios SET del = '1' WHERE id = '".$Link."'";
mysql_query($query) or die ('Error: ' . mysql_error());
//header('Location: http://google.es'); //For debug
}
}
echo '<form name="del" method="post">
<input type="hidden" name="del_link" value="'.$rowComen['id'].'" />
Delete
</form>';
But when I press the link the web refreshes and that's all...
I had tried with: header('Location: http://google.es'); But I don't redirect to google...
And I don't know if the problem is in the post or in the query...
if(isset($_POST['del'])) {
You dont seem to have del form field. so the code inside this if statement is never executed. i think you are trying to check for del_link. so make it as if(isset($_POST['del_link'])) {
Have you checked in your browser if it contains the right value? The form as it is will contain the exact value '.$rowComen['id'].', unless a part of the PHP code is missing and the form is actually inside a string..
[edit]
I see. The form's name is 'del', but that name is never sent. Make the name of your submit button 'del', or add another hidden element. Easier still: Just check for the existence of del_link instead of del:
if(isset($_POST['del_link'])) {
$Link = $_POST['del_link'];

Javascript/PHP interaction only appears on second click

Have searched for the answer but no joy, so here goes...
I'm working on a mobile hybrid app. I want the user to fill in their id number, which is then submitted to a javascript function for basic validation, then kicks in a jQuery.getJSON request to my serverside PHP which returns the data and then my jQuery will repopulate the form div with the data.
Currently it doesn't really work at all in Firefox, and only works correctly in Safari after I press the submit button for a second time. It returns the correct data, so the link is ok.
My problem is: Why does the div not get repopulated after the first click?
HTML:
<div id="login540div">
<form id="login540form" onSubmit="login540()">
Enter Student ID number<input type="text" name="login540id" id="login540id"/>
<input type="submit" value="Submit" />
</form>
</div>
Javascript:
function login540(){
// validates the data entered is an integer.
var loginNo = document.getElementById("login540id").value;
//if(!isNaN(loginNo))
if((parseFloat(loginNo) == parseInt(loginNo)) && !isNaN(loginNo))
{
//jSonCaller(loginNo);
$.getJSON('http://localhost:8888/c05673160/login540.php?q='+loginNo, function(data){
//alert(data);
$('#login540div').html("<p>First Name ="+
data.firstName+
"</p> Last Name ="+data.lastName+" </p>Module No.1 ="+
data.moduleNo1+"</p> Module No.2 ="+
data.moduleNo2+"<p> Course ID="+
data.courseID+"</p>");
})
}
else
{
// alert(loginNo); CHECKED
alert("Please make sure to insert only a whole number");
}
Then the PHP goes like this...
<?php
include ("config.php");
/*
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$var = array('i'=>10, 'j'=>20);
$firephp->log($var, 'Iterators');
*/
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData';
$q=$_GET["q"];
$table = "studentTable";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table} WHERE studentID = '".$q."'");
if (!$result)
die("Query to show fields from table failed!" . mysql_error());
$json = array();
while($row = mysql_fetch_array ($result))
{
$json = array(
'firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'moduleNo1' => $row['moduleNo1'],
'moduleNo2' => $row['moduleNo2'],
'courseID' => $row['courseID']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close($conn);
?>
I can't figure out what's wrong, and I've been messing around with various things for the last few days trying to fix it, but no joy, so I'd really appreciate any help you can give.
#Robbie had a good point that you don't appear to be stopping the default behavior of the form submission. To do this you need to change a couple things:
onSubmit="login540()" needs to change to onSubmit="return login540()" otherwise whatever you return from the login540() function will be ignored.
At the end of the login540() function you need to return false; to stop the form from submitting normally. You can also pass in the event object as the first argument and use event.preventDefault() instead: function login540(event){event.preventDefault();...}.
To do yourself a favor however, you can use jQuery to bind the submit event handler to the form rather than using inline JS (tisk, tisk, :) )
$('#login540form').on('submit', login540);
This way you can keep all of your JS in one place rather than spread-out all over your HTML.
The bottom of Function login540() is missing, but this needs to kill the default "submit" action: this can be done with "return false;" at the end. As I can't see the end, not sure if this happens or not, but the form probably "submits" while the AJAX is running.
This is compounded as the form doesn't have an action, which probably explains the different browser behaviour. I suggest setting action to "#" and then, if you see "#" added in the URL then the form has submitted and not been stopped by your function.

Categories