I'm working on PHP at the moment.
I have a form seen below with a submit button.
I then created a function below also.
As you can see the first thing the function does is checked the submit button is pressed, but it goes into this if upon loading the page(i don't need to press the button), and it out puts the "Entry Submitted" p tag autmoatically, where it shouldn't even be entering the first if statement.
Any help appreciated,
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" tabindex="100"/>
<br />`enter code here`
</p>
</form>
<?php
if (isset($_POST['Submit'])){
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'auser';
$mysql_pass = 'auser';
$mysql_db = 'ourwebdb';
// Connect to database
if (!#mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !#mysql_select_db($mysql_db)) {
die ($conn_error);
}else {
//echo 'Connected';
// Perform database insert
$name = $_POST["Name"];
$email = $_POST["email"];
$teamSupported = $_POST["radioGroup"];
$comment = $_POST["comment"];
$query = "INSERT INTO visitors (Name, Email,[Supported Team], Comment)
VALUES ('{$name}', '{$email}', '{$teamSupported}', '{$comment}')";
$result = mysql_query($query);
if ($result) {
// Success
$id = mysql_insert_id();
echo '<p> Entry Submitted</p>';
// Do something
} else {
die ("Database query failed. ". mysql_error());
}
}
}
mysql_close();
Change your 1st PHP line
if (isset($_POST['Submit'])){
to
if (isset($_POST['Submit']) && $_POST['Submit']=='Submit' ){
there is nothing wrong in your code (except cut out portion of form). so there is two possible scenario 1. you are refreshing browser url with re-submit 2. there are some onload javascript/jquery function which submit the page (form.submit()..)
Solution for 1. is easy just open the url in new tab. for scenario 2. you need to check Or submit your full code here
Related
I have three files working on an login app to learn PHP.
This is the connection with DB
<?php
# Connecting database below
$connection = mysqli_connect('localhost','root','','loginapp');
if ($connection) {
# code...
echo "connected";
}
else{
echo "Errorr";
die("Database");
}?>
and here is the html code for the web view
<html>
<head>
<title>Form</title>
</head>
<body>
<h1>Welcome to My Form</h1>
<form class="" action="login_create.php" method="post">
<input type="text" name="name" placeholder="Enter your name here"><br>
<input type="password" name="password" placeholder="Enter Password" value=""><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
and here is the file where things are going wrong, its not checking the conditions of entries and not putting the data into database what's wrong going there? help please
sometimes it gives
error that "unknown 'sbumit' in the $_POST" and sometimes it don't
doesn't even show any error
but doesn't even do anything
<?php
include "db.php";
if (isset($_POST['submit'])) {
$username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
if (strlen($username) > 10 && strlen($username) < 3) {
echo "Must enter username & pass between 3 & 10";
echo "So that we can forward your request";
}
else {
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')";
$result = mysqli_query($connection,$query);
if(!$result)
{
die('Sorry Query faild'.mysqli_error());
}
}
}
else
{
echo "You haven't wrote anything, write it first";
}
}?>
Habib,
Some guidance for PHP :
$button = isset($_POST["submit"])?$_POST["submit"]:"";
What this line does is apply a value to the $button variable, the first check is that IF isset($var) THEN (indicated with the ? ) apply the value of $var to the $button variable.
The colon : then sets that if the boolean query (true/false) of the IF returns false, then apply the second value instead, in this case an empty string of "".
This is code minimalisation and you should be aware of it but there is little need to use it, especially while learning.
Feedback on your code:
mysqli_error($connection); Your error feedback for MySQLi should include the connection details, as shown here.
replace the $username = $_POST['name'];
$password = $_POST['password'];
if (isset($username) && isset($password)) {
because you want to check not if they're set but if they're not empty, currently they will be set as they're set to the values of $_POST even if they are null (potentially), so replace with:
if(!empty($username) && !empty($password)){
Also note that ! is the negative operator. so above is IF NOT EMPTY.
if (strlen($username) > 10 && strlen($username) < 3) { this is impossible to reach because you're setting if string is longer then 10 AND string is shorter than 3, this is clearly impossible. replace the && with || which is OR rather than AND .
Personally I think that isset($_POST['submit']) is not the best way, instead checking that if($_POST['submit'] == 'submit') confirms the submission of this form from this submit button (the value is the value set in your HTML form).
$query = "INSERT INTO users (username,password) VALUES ('$username','$password')"; This works fine, BUT you really, really need to do some research into SQL injection attacks and SQL security. read How can I prevent SQL injection in PHP? as a start. This is very important to learn at the start of your PHP MySQL learning.
Also research into PDO database connectivity.
Also be aware that your script will not output anything when you have a successful saving of username/password to the database.
As a closer:
Fnally, set up error logging on your page, to give you useful feedback on errors and problems: error_reporting(E_ALL);
ini_set('display_errors', 1); at the very top of your page. Also see How do I get PHP errors to display?
Change your code as follow.
<?php
include "db.php";
$button = isset($_POST["submit"])?$_POST["submit"]:"";
$username = isset($_POST["name"])?$_POST["name"]:"";
$password = isset($_POST["password "])?$_POST["password "]:"";
/*Commetents*/
$button =isset($_POST["submit"])?$_POST["submit"]:"";
is similar to following code:
if(isset($_POST["submit"]))
{
$button = $_POST["submit"];
}
else
{
$button = $_POST["submit"];
}
You know in Php 5.4 , it will present error,if you do not set any value to variable . that is why we used it. If it doesn't get any value it will set it value "".
if($button == "submit") means when someone will press the button submit then $_POST['submit'] value will be submit which you define in the submit button value.
if($button == "submit")
{
if($username=="" or $password=="")
{
$error ="Username & Password can't be blank";
}
elseif(strlen($username)<3 or strlen($username) > 10 )
{
$error ="Must enter username & pass between 3 & 10";
}
else
{
$query = "INSERT INTO users (username,password) VALUES('$username','$password')";
mysqli_query($connection,$query) or die(mysqli_error());
}
}
echo $error;
Hope it will help you .
This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}
My site is an admin login site, therefore users cannot register. However they can post comments to the site. I have delete buttons on the comments but didn't realise that anybody can then delete anybodies comments. How can I change this so when the admin is logged in they are able to delete inappropriate comments (if any) and get rid of the delete button from the general public.
This is my Comment.php code with the delete button function in there:
<?php
session_start();
require_once 'templates/open.php';
require_once 'connect.php';
require_once 'functions/cleanstring.php';
require_once 'functions/encrypt.php';
?>
Another code file:
<?php
$db_hostname = 'localhost';
$db_database = 'cs12e2g_MyFirstDB'; //'Your database name'
$db_username = 'cs12e2g_DBuser'; //'your username';
$db_password = 'vtjppqs7'; //'Your password';
$db_status = 'not initialised';
$db_server = mysqli_connect($db_hostname, $db_username, $db_password);
$db_status = "connected";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}
// Includes and variables always required
require_once 'recaptcha/recaptchalib.php';
require_once 'functions/cleanstring.php';
$privatekey = "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
mysqli_select_db($db_server, $db_database);
$str_message = "";
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
}else{
if(isset($_GET['delete'])){
$deleteq="DELETE FROM comments WHERE ID={$_GET['delete']} LIMIT 1";
$deleter=mysqli_query($db_server, $deleteq);
IF($deleter){
echo"<p>That message was deleted!</p>";}}
//Test whether form has been submitted
if(trim($_POST['submit']) == "Submit"){
//Handle submission
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
$str_message = "The reCAPTCHA wasn't entered correctly. Go back and try it
again.
(reCAPTCHA said: " . $resp->error . ")";
} else {
// Your code here to handle a successful verification
$comment = $_POST['comment'];
if($comment != ""){
$query = "INSERT INTO comments (comment) VALUES ('$comment')";
mysqli_query($db_server, $query) or die("Comment insert failed: " .
mysqli_error($db_server) );
$str_message = "Thanks for your comment!";
}else{
$str_message = "Invalid form submission";
}
}
}
//Create page with or without submission
$query = "SELECT * FROM comments";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) );
while($row = mysqli_fetch_array($result)){
$ID= $row['ID'];
$str_result .= "<p><em>Comment $j (" . $row['commDate'] .
")</em><br /> " .$row['comment'] . "</p>
<a href ='commentnow.php?delete=$ID
'>Delete</a><hr />";
}
mysqli_free_result($result);
}
?>
<h1>What do you think?</h1>
<p><h5>Did you find everything you wanted? Please comment below:<h5></p>
<form action="commentnow.php" method="post">
<textarea rows="10" cols="50" name="comment"></textarea><br />
<?php echo recaptcha_get_html($publickey); ?>
<input type="submit" name="submit" value="Submit" />
</form>
<span style="color:#FF0000;">
<?php echo $str_message; ?></span>
<hr />
<h2>Comments:</h2>
<?php echo $str_result; ?>
</div>
<?php
require_once 'templates/close.php';
?>
I have a members.php page which corresponds to when the admin logs in (they are the only ones that can access this page) would the delete button code have to go in here? so they are the only ones that can use the function? If so where would it go, and how?
Restrict the delete button to show only for the admin. Also this would mean that you somehow identify if the logged in user is an admin.
if ($is_admin) {
// Code to display button
}
Also in the backend check if the logged in user is admin
if ($is_admin) {
// Code to delete comment
delete_comment();
}
and you welcome to php.
You have that identify the users that enter in your application.
Using database or arrays or files or variables etc etc.
If permission is equal to admin or editor (For example) allow delete.
For example
if( $login == 'admin' ){
// Allow action
}
My you understand?
(My English is bad, sorry)
I have the following scripts. The user will pass a numerical value e.g. 123 as a parameter in the URL, and the app will load/fetch that value from MySQL and show it in the textarea.
E.g., entering, "example.com/index.php?id=123" in the URL will pull the 123rd record from the database and show it in the textarea. Everything seems to be working, but I want to show the last row/id of the "source" table when the form is submitted. So, instead of showing "Saved!" in the pop-up, it should show something like "124" (or, the last updated row/number).
index.php:
<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
$id = $_GET['id'];
$result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error());
$row = mysql_fetch_array($result);
if($row)
{
$submit_date = date("Ymd");
$content = $row['content'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myform").submit( function () {
$.post(
'submit.php',
$(this).serialize(),
//
// show the last id here!
//
function(data){ alert("Saved!"); }
);
return false;
});
});
</script>
</head>
<body>
<div id="header" >
<form action="submit.php" method="post" id="myform">
<textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
<br/>
<input type="submit" name="submit" value="Submit" id="submit"/>
</form>
</div>
</body>
</html>
submit.php:
<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') {
//
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>
connect-db:
<?php
$server = 'localhost';
$user = 'domdom';
$pass = 'password#123';
$db = 'domdom';
$connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... \n" . mysql_error ());
mysql_select_db($db) or die ("Could not connect to database ... \n" . mysql_error ());
?>
Please note that I do not need any advice on PDO or MySQLi, that is not important at this time. However, any suggestions on improving the security/SQL query etc. are welcome. Thanks.
I will try to answer in 2 parts:
[1] PHP side: in the "isset($_GET['id'])" section, just return the content of the text area you want to fill out. Say, in your DB, 123 -> 'Friday'. Just return the String 'Friday'.
[2] Client side: Do not "submit" the form. Call a JS function, and in there, create an XmlHttpRequest, and send the request to the server as an AJAX request. When you get the return value, examine it and populate your HTML textarea.
If you think this method is suitable for you and you need more details, let me know. I do this in many of my sites.
I am quite new to PHP, and still have long way to go. Probably, it is a logic failure or maybe I just dont know how exactly PHP works.
Anyway, The code I submited is from my admin control panel. I am trying to make a page to connect to db than show all db names and select one of them from radio buttons. And when pressed submit again to show tables.After showing table the next step will be to edit,add update them etc. I am not there yet. Because I could not make mysql_select_db to work. It gives error.
The error is;
Notice: Undefined variable: connect in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Warning: mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /public_html/php/insert_delete_update_amend/mydata03.php on line 94
Could not connect to db
Any help will be much appreciated.
P.S.: Also when the first form is submitted,first form disappears and second one appears and so on.
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
if($DisplayDBinfoForm) {
?>
<form name="dbinfo" method="POST" action="mydata03.php" onsubmit="return validateForm();">
Host Name: <input type="text" name="db_name" /><br />
<br />
DB User Name <input type="text" name="db_user_name" /><br />
<br />
DB User Password: <input type="text" name="db_user_password" /><br />
<br />
<input type="submit" name="db_info_submit"value="Login"><br />
</form>
<?php
}
if($DisplayDBform) {
?>
<form name="delete_table" id="delete_table" action="mydata03.php" method="post">
<table width="30%" border="1">
<tbody>
<?php
$query = "SHOW DATABASES";
$resultSet = mysql_query($query);
while($database = mysql_fetch_array($resultSet)) { // go through each row that was returned in $result
$dbname = $database[0];
echo "<tr><th>Database Name</th>
<th>Select</th>
</tr>
<tr>
<td>$dbname</td>
<td><input name=\"radDB\" id=\"radDB\" type=\"radio\" value=\"$dbname\"</td>
</tr>\n";
}
?>
</tbody>
</table>
<p>
<input name="btnSelectDB" type="submit" value="Select" />
</form>
</p>
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>
First off, don't use mysql_* functions. That time has passed. Instead, use mysqli_* or PDO.
With that said, it appears that the initial connection to the database server complete fine, as your code doesn't crap out on you at:
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
Although at the later stage, when trying to connect to an actual database: $select_db = mysql_select_db($db_name,$connect); it does.
This leaves me to believe that the variable in which you set the database name $db_name = $_REQUEST["radDB"]; is not pulling the data in correctly.
try
$connect = mysql_connect($hostname,$db_user_name,$db_user_password) or die("Could not connect");
if( $connect)
echo "<p><b>connected successfully</b></p>\n";
}
also check that the
if( isset($_POST['db_name'] ) && isset($_POST['db_user_name']) && isset($_POST['db_user_password']){
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
Use of this extension(MYSQL_*) is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used
Good Read
PDO Tutorial for MySQL Developers
The problem you have is that the database is only opened ($connect=) if you have done a post with 'db_info_submit', but you can still run line 94 if you have posted 'btnSelectDB'.
Simplest solution is to open the database outside the if ($_POST) statement at the top, in case it's needed below. Or wrap in either of the conditions required to open it (code shown below)
<?php
// form variables
$DisplayDBinfoForm = true;
$DisplayDBform = false;
if (isset($_POST['db_info_submit']) || isset($_POST['btnSelectDB'])) {
$connect = mysql_connect($hostname,$db_user_name,$db_user_password);
if(!$connect) die("Could not connect");
echo "<p><b>connected successfully</b></p>\n";
}
}
if (isset($_POST['db_info_submit'])) { //when user presses db info submit button
//select which form to hide or appear
$DisplayDBinfoForm = false;
$DisplayDBform = true;
$hostname = $_POST['db_name'];
$db_user_name = $_POST['db_user_name'];
$db_user_password = $_POST['db_user_password'];
}
if($DisplayDBinfoForm) {
?>
....
<?php
}
if(isset($_POST['btnSelectDB'])) {
$DisplayDBinfoForm = false; // hide form
$DisplayDBform = false; // hide form
$db_name = $_REQUEST["radDB"]; // the db na,e
echo "The " . $db_name . " is selected\n";
$select_db = mysql_select_db($db_name,$connect);
if(!$select_db) die("Could not connect to db". mysql_error());
echo "<b>connected successfully to db</b>";
}
?>
This isn't a direct answer, but it's the answer that's goign to help you the most.
If you have a function in your script that begins "myslq_" (except for 1 - mysql_real_esacape_string) then you're following an old example and are using code that is going to be depreciated. As you're just learning PHP and MySQL, get into the habits of using the more modern functions, either mysqli_ or PDO