Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm a beginner in PHP and MySQL and I want to add values that come from an input in HTML, to a MySQL database.
I have to find some things on the Internet but this doesn't work and so I tried to learn a little bit more PHP but I still don't understand why the condition in the code below is not valid:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
<?php
echo "test1";
if (isset($_POST['name'])) {
echo "test2";
$mtsqli = mysqli_connect('localhost','the_name_of_my_project','my_password');
mysqli_select_db('project_database', $msqli);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
$query = "SELECT * FROM the_name_of_the_database's_table";
echo $_POST['name'];
echo "test3";
}
?>
</body>
</html>
I'm on this for 3 days and I'm really blocked. Maybe I have others mistake in the PHP code. If I can do that with another language i prefer to stay on PHP because I don't want to learn too much languages. If I can do a bridge between HTML and MySQL with Python or JavaScript I'm OK to know that.
THIS PART IS GOOD but another problem is come ...
when i want to connect on my database this error message is display
C:\Users\titou>set PATH=$PATH$;C:\Program Files\MySQL\MySQL Server 8.0\bin
C:\Users\titou>mysql -h localhost -u root -p
Enter password: **********
ERROR 1045 (28000): AccŠs refus‚ pour l'utilisateur: 'root'#'#localhost' (mot de passe: OUI)
its in french but you can see that there is two # instand of one ('root'#'localhost')
First you need to add a Form Method
<form action="" method="POST">
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</form>
The is some kind of class that tells the browser to expect inputs and then on the button click- to treat them.
The Action="" is for initializing where to treat the given inputs.
In your case, since your php code is in the same class as the form, you can leave it blank, either way you should initialize the path you want to send those data.
The Method="POST" is just a Method for treating your data on the web. It is also more secure than GET method which it works too but it's more sensitive since all the data from the inputs it's going to be exposed also in the URL.
Furthermore, I hope you have already installed XAMPP and already created a database in MySQL.
Add the form attribute to your form and in it add a method and an action. Method is needed to tell the form to post, and action is needed to tell the form what to do when you submit.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8">
<title>SHAR-APP</title>
</head>
<body>
<form method="post" action="">
<div class='div1'>
<div class='div2'>
<label for="name">Name of the user:</label>
<input class ='in'type="text" id="name" name="name" size="20">
</div>
<div class='div2'>
<label class = 'label' for="name">Code:</label>
<input class='in' id ='code' type="text" name="code" size="20">
</div>
<div class="div2" id='b'>
<input type="submit" value="send" class='button'>
</div>
</div>
</form>
<?php
if (isset($_POST['name'])) {
$db = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$requete = 'INSERT INTO the_name_of_the_database's_table VALUES(NULL,"' . $_POST['name'] . '","' . $_POST['code'] . '")';
mysqli_query($db, $requete);
$query = "SELECT * FROM the_name_of_the_database's_table";
$Data = mysqli_query($db, $query);
var_dump[$Data];
}
?>
</body>
</html>
Now an important thing to note, never use this in a live website as it would open up your website to SQL injection. You should use prepared statements instead, but for learning purposes, this is fine.
Related
Hey i'm having a problem where I cannot seem to get the value of an input using PHP, I have a form in HTML and another file named "handle.php" which i prints the value of username but when I submit It directs me to the file "handle.php" and does not print anything, just shows the script.
I tried doing the script inside the HTML but I got the same result, nothing happened so I thought maybe I need to make a function and then call it onclick but it didn't do anything eventually I made a separate file named "handle.php" and in the form I did "action="handle.php" which lead to the first problem.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> Hide/Show Password Login Form</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="login_form">
<section class="login-wrapper">
<div class="logo">
<img src="logo.png" alt=""></a>
</div>
<form id="login" method="post" action="handle.php">
<label for="username">User Name</label>
<input required name="login[username]" type="text" autocapitalize="off" autocorrect="off" />
<label for="password">Password</label>
<input class="password" required name="login[password]" type="password" />
<div class="hide-show">
<span>Show</span>
</div>
<button type="submit">Sign In</button>
</form>
</section>
</div>
</body>
</html>
handle.php:
<?php
echo $_POST['login[username]'];
?>
By using this name="login[password]" you can get the values in PHP as:
print($_POST['login']['password']);
One more solution, store input array in a variable like:
$post = $_POST['login'];
then, use like:
echo $post['password']
$_POST['login']; will return a php array with all keys you used in your form. So you get the username key of this array like this:
echo $_POST['login']['username'];
first try to print only $_POST then you see what is you get in request.
always help to you for following this method. debug step by step then get the data into array.
<?php
$request=$_POST['login'];
echo $request["username"];
echo $request["password"];
?>
Replace textbox name as username in html code and Change php code as echo $_POST['username']; in handle.php
In Html code,
<input required name="username" type="text" autocapitalize="off" autocorrect="off" />
In php code( handle.php),
echo $_POST['username'];
I am a complete beginner when it comes to PHP. I have successfully created a login form/page that requires a user to enter his/her username and password which is then added to a database. I have also managed to create a page (using php) to display the data contained in all the data fields. I have the db connection file separately which works well. I have a functions.php file which contains the functions.
Now, I have created a php file in which I should be able to update the data in the various fields in the database. Instead of updating/replacing the existing data (username & password) in the selected row (targeting the id) it creates a new row in the db with the new username & password. Herewith my code to update existing data fields.
<?php include "db.php";?>
<?php include "functions.php";?>
<?php
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$id = $_POST['id'];
$query = "UPDATE users SET ";
$query .= "username = '$username', ";
$query .= "password = '$password', ";
$query .= "WHERE id = $id ";
$result = mysqli_query($connection, $query);
if(!$result) {
die("QUERY FAILED" . mysqli_error($connection));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="col-sm-6">
<form action="login_create.php" method="post">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" class="form-control">
</div>
<div class="form-group">
<select name="id" id="">
<?php
showAllData();
?>
</select>
</div>
<input class="btn btn-primary" type="submit" name="submit" value="UPDATE">
</form>
</div>
</div>
</body>
</html>
I can simply not find the problem. Since people use PHP differently I am unable to find a solution based on the specific coding I have tried.
Update
Kindly note that I am working on a localhost as part of learning php and have not yet started looking at security. I am initialising the $connection via a different file (db.php) which I am calling in the first line of my previous code.
<?php
$connection = mysqli_connect('localhost', 'root', '', 'loginapp');
if(!$connection) {
die("Database connection failed");
}
?>
Since you didn't say what does the login_create.php do and what is the filename of that php code in your post. I can only guess that your login_create.php file is to create a new account not update it. Perhaps your file with that UPDATE query is not named login_create.php. Hence, my guess is that you put a wrong filename in your <form action="login_create.php" method="post">
(Posted solution on behalf of the question author).
The problem was with the incorrect naming of the form action. I used
<form action="login_create.php" method="post">
instead of
<form action="login_update.php" method="post">
I have tried putting together a basic jQuery Mobile page that connects to another file on the same path of the server to send the data. I have tested the PHP by itself in the commented out part of code.
The PHP File - submit harvest.php
$dbConnection = mysqli_connect('*********', '*********', '*********', '*********');
/*
$variety = "Aji Limon";
$picked = "11";
$weight = "22";
*/
$variety = $_POST['variety'];
$picked = $_POST['picked'];
$weight = $_POST['weight'];
$query = "INSERT INTO `harvest` (`variety`, `picked`, `weight`) VALUES ('$variety', '$picked', '$weight')";
if (mysqli_query($dbConnection, $query)) {
echo "Successfully inserted " . mysqli_affected_rows($dbConnection) . " row";
} else {
echo "Error occurred: " . mysqli_error($dbConnection);
}
?>
And the html file - index.html
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<!--Mobile Device Scaling -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0" />
</head>
<body>
<div data-role="page" id="harvest">
<div data-role="header" data-theme="b">
<h1>Chilli Harvest</h1>
</div>
<div data-role="content">
<form name="harvest" action="submitharvest.php" method="post" data-ajax="false">
<div data-role="fieldcontain">
<label for="variety" class="select" >Variety:</label>
<select name="variety" id="variety" data-theme="b">
<option value="7 Pot Red">7 Pot Red</option>
<option value="7 Pot Yellow">7 Pot Yellow</option>
<option value="Aji Limon">Aji Limon</option>
</select>
</div>
<div data-role="fieldcontain">
<label for="picked">Qty Picked:</label>
<input type="range" name="picked" id="picked" value="1" min="0" max="200" step="1" data-theme="b" data-track-theme="c"/>
</div>
<div data-role="fieldcontain">
<label for="weight">Weight (g):</label>
<input type="number" name="weight" id="weight" value="" data-theme="b" />
</div>
<div data-role="fieldcontain">
<input type="submit" value="Send" id="submit">
</div>
</form>
</div>
</div>
</body>
</html>
Having added the data-ajax="false" and even removing the entire query mobile framework I get the same problem of the php stating "Error Occurred" with no extra detail following it, I can't see anything going wring in the console either. Hopefully I'mm missing something very basic here? Please help.
So having tried a few things from the first couple of comments below - would it also be that the dbconnection being the culprit? I am using a NAS drive with personal MySQL database on it, do I need to speify the port number at the end? Currently I have:
$dbConnection = mysqli_connect('home IP Address:3306', 'username', 'password', 'databasename');
I have seen some connection strings like this where port numbers are involved:
$dbConnection = mysqli_connect('home IP Address', 'username', 'password', 'database name', 3306);
Which really adds to my confusion as I have tried all of the above and even putting the port number in "3306"... Stumped, anyone got any further ideas please?
Turns out after many hours of wasting time the web server that it was hosted on was blocking the MySQL via it's Firewall, so all my check were ok but the web host firewall was to blame and the web company have added an exclusion to allow this to work!
I've written some html code, and once i tried to place some PHP inside it, anything below this sign ?> wouldn't appear!!! I have some pictures and text that wouldn't appear unless I place it above. I'm writing with Bootstrap 2.3 and phpMyAdmin 4.10. all languages. Thank you for your time in advance.
here is my code so far:
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassowrd" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassowrd" placeholder="Your password">
<input class = "btn btn-default" type="submit" value="Sign in">
</form>
<?php
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
header("location:index.php");
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
?>
</div>
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
</body>
</html>
A few things have already been outlined (as answers) that do make sense, however I spotted a few typos in your inputs that will prevent your form from working, plus a few other points.
Here are a few of my recommendations:
First, this (in 2 instances) has a typo in it name="usrPassowrd" which should read as name="usrPassword" to go with your existing $password = $_POST['usrPassword'];
As I stated in my original comments:
Comment #1: die("cannot go empty"); header("location:index.php"); exit; Your header won't do anything, because it DIE()'d and that will cease to go any further.
Comment #2: What I suspect is going on is, because you've got your entire code inside one big clump, and that if certain conditions aren't met... it still wants to keep going. Now, I suggest that you put a conditional statement wrapped around your PHP....
such as if(isset($_POST['submit'])){ // PHP } then add this to your submit button name="submit" --- I also suggest you split up your form and your PHP/SQL altogether and make it submit to another page instead, with the same conditional statement I've already outlined.
If you absolutely want to execute everything in one page, try the following:
Note: I borrowed the img src from user3009875's answer also.
(Rewrite)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="bootstrap/css/bootstrap.css">
<link type="text/css" rel="stylesheet" href="bootstrap/css/myStyle.css">
<title>OJRA - Registration</title>
</head>
<body>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username</h6>
<input type="text" name="username" placeholder="Your Username">
<h6>Password</h6>
<input type="password" name="usrPassword" placeholder="Your password">
<h6>Email</h6>
<input type="email" name="usrEmail" placeholder="Your Email"><br>
<input class = "btn btn-default" type="submit" value = "Register">
</form>
</div>
<div style="width:400px; height:400px; border-radius:5px; background-color:#aaa; margin-left:100px;">
<form action="" method="post" style="margin-left:20px;">
<h6>Username:</h6> <input type="text" name="username" placeholder="Your username">
<h6>Password:</h6> <input type="password" name="usrPassword" placeholder="Your password">
<input class = "btn btn-default" name="submit" type="submit" value="Sign in">
</form>
<?php
// this below, will prevent a premature execution of code
if(isset($_POST['submit'])){
define('INCLUDE_CHECK',true);
require 'connect.php';
$username = $_POST['username'];
if($username == "")
{
die("cannot go empty");
// header("location:index.php"); // commented out
exit;
}
$password = $_POST['usrPassword'];
$email = $_POST['usrEmail'];
$query = "insert into tz_members values('$username', '$password', '$email')";
mysql_query($query) or die(mysql_error());
} // end brace for if(isset($_POST['submit']))
?>
</div>
<!-- commented out original img src -->
<!--
<img src="sexymotivation.jpg" style="margin-top:-800px; margin-right:10px;" class="pull-right">
-->
<!-- new img src by user3009875 in an answer given -->
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
</body>
</html>
You can't use header() there to perform a redirection because you've already outputted some HTML and PHP has flushed HTTP headers.
The reason that <img> disappeared is probably that you called die(). This function terminates the whole page at once.
If you see cannot go empty, you should check the form to make sure you posted username field. If you see some error message about MYSQL, it is mysql_query($query) that fails.
By the way, your code has a SQL Injection problem.
IT doesn't load below ?> because script fails. This is common behaviour when there is a bug.
Check tail -f /var/log/apache2/error.log on linux (terminal)
Check tail -f /var/log/apache2/error_log on max (terminal)
windows -> I have no idea... somewhere in C:\\
At this point:
die("cannot go empty");
you stop the script. The following PHP code will not be executed and the HTML will not be sent to the user.
It's possible that there is an error when executing your PHP code, that would prevent it from going through the rest of the file.
Using your browser's Developer Tools, check the contents of the HTML that was returned, it's possible that the last line could be an error message. If you have erorr_reporting off then it would write to your error log only.
/var/log/apache2/error.log is a common location for the error log file if you are using Apache on a Linux machine.
As a side note, that code you have is very dangerous, do not use data sent from the client directly in a SQL statement, you need to sanitize otherwise you make your web app vulnerable to SQL injection.
Consider using a prepared statement
http://php.net/manual/en/pdo.prepare.php
Try:
<img src="sexymotivation.jpg" style="margin-top:100px; margin-right:10px;" class="pull-right">
I think setting the top margin to -800px will cause it to disappear from the screen.
Also, make sure your image is of .jpg.
I'm building my first PHP website (attempting to, anyway!), and I'm trying to create a contact form whose contents are submitted to me via email. I've got the email part down, but I'm having trouble getting the form ("contact.php") to accept data. It automatically refreshes as soon as I type a character in any field. Here's the relevant code:
<div class="contactform">
<form name="contactform" method="post" action="contact-receiver.php">
<fieldset><legend><strong>Required Information</strong></legend>
First Name: <input type="text" name="firstName" size="35" maxlength="30"/>
Last Name: <input type="text" name="lastName" size="35" maxlength="30"/>
Email: <input type="text" name="emailAddress" size="60" maxlength="55"/>
</fieldset>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
This works fine when tested independent from the rest of the site. However, here's the context:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<?php include 'header.php'; ?>
<?php
$id = $_GET['id'];
switch($id)
{
case 'main':
include 'storeinfo.php';
break;
case 'shop':
include 'inventory.php';
break;
case 'cart':
include 'cart.php';
break;
case 'contact':
include 'contact.php';
break;
default:
include 'error.php';
}
?>
<?php include 'footer.php'; ?>
</body>
</html>
"contact.php" works fine when displayed as a separate page, but won't accept any input when accessed as an include file. If I try to enter data in any of the fields, the page immediately refreshes after I type the first character, and the data is lost.
If anyone could point me in the right direction, I would really appreciate it!
EDIT
Disabling Javascript didn't work. I cleared my cache and restarted my browser (Firefox) just to be sure. While I'm working on that voodoo priest, here's the page source for index.php?id=contact:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Main</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<div>
<p><img src='headerimg.png' class='header'/></p><a href='index.php?id=main'>
<img src='mainbutton.png' class='nav1'</a><a href='index.php?id=shop'>
<img src='shopbutton.png' class='nav2'</a><a href='index.php?id=cart'>
<img src='cartbutton.png' class='nav2'</a><a href='index.php?id=contact'>
<img src='contactbutton.png' class='nav2'</a>
</div>
<div class="contactform">
<form name="contactform" method="post" action="contact-receiver.php">
<fieldset><legend><strong>Required Information</strong></legend>
First Name: <input type="text" name="firstName" size="35" maxlength="30"/>
Last Name: <input type="text" name="lastName" size="35" maxlength="30"/>
Email: <input type="text" name="emailAddress" size="60" maxlength="55"/>
</fieldset>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
<div id = "footer">
<p>©2012</p>
</div>
</body>
</html>
It sounds like a Javascript-related problem.
Check and make sure you're not including any scripts which try to autocomplete, as being misconfigured might cause it to send a request upon key up which would cause the behavior you're mentioning.
An easy way to test this is to disable JavaScript in your browser and see if the issue continues. If it does, it means you have ghosts in your computer and should see a voodoo priest. If the issue doesn't persist, it means it's an issue with some JavaScript on your site.
Posting some contents of header.php will help, as well. OR, you could simply post the complete HTML page source once - that is, visit your index.php?id=contact page, hit view source, and show that here.