I have problem to get my code working in php
I want to move data from a form in html to my mysql database but it dont work??
Form part
<form action ="Mydbsinsertpersson4.php" method='POST'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
the php part
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn)
VALUES ('".$_POST["fnamn"]."','".$_POST["enamn"]."')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
the connection to my mysql database works i can get data from the database but not input to it.
Thanks in the advanced.
This is on of many solutions i have tried non have worked!!
The problem is :-
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
And you write:-
if(isset($_POST["submit"])){
Note:- either change name = submit in first one or change $_POST["Submit"] in second one. Thanks.
I like to do this using two files, one for handling the inputs and one for the actual form.
form.html:
<form action ="/assets/post_people.php" method='POST'>
<table>
<tr><td width='100'>Firstname:<input type='text' name='fname'><td></tr>
<tr><td width='100'>Lastname:<input type='text' name='lname'><td></tr>
</table>
<tr><td><input type='submit' name='Submit' value='Submit'><td></tr>
</form>
Now, for post_people.php:
<?php
//db
require_once 'db_connect.php';
//Get and filter input # to avoid injections
$Firstname = mysql_real_escape_string($_POST['fname']);
$Lastname = mysql_real_escape_string($_POST['lname']);
//Check if the user has submitted the form
if(isset($_POST['Submit'])){
//Check if the person already exist in our database
$Check_people = mysql_query("SELECT * FROM People WHERE Firstname = '$Firstname' AND Lastname = '$Lastname'");
if(mysql_num_rows($Check_people)==1){
//The person already exists with exact same data!
}
//The person did not exist in our database, so we'll update.
else{
$update_query = mysql_query("INSERT INTO People (Firstname, Lastname) VALUES ('$Firstname', '$Lastname')");
if($update_query){
//success
}
else {
//Error
}
}
mysql_close();
}
//The user didnt submit the form and tried to access the file ?
//Redirect to /form.html & kill the script.
else{
header("Location: /form.html");
die;
}
I don't know if this will work for you, but it did work for me :)
(Yes im well aware that you shouldn't use mysql_ functions as they are depreciated but they are still working and are easy to use :))
Errors
Incorrect in submit tag name name='Submit'
improve your HTML codeing format(</table> tag should close after last </tr> tag)
Avoid SQL Injections by using mysql_real_escape_string()
So your final code would be
<form action ="Mydbsinsertpersson4.php" method='post'>
<table>
<tr><td width='100'>För namn:<input type='text' name='fnamn'><td></tr>
<tr><td width='100'>Efternamn:<input type='text' name='enamn'><td></tr>
<tr><td><input type='submit' name='submit' value='Submit'><td></tr>
</table>
</form>
In Mydbsinsertpersson4.php
<?php
if(isset($_POST["submit"])){
require_once 'Mydbconfig.php';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $mysqli->real_escape_string($_POST["fnamn"]);
$ename = $mysqli->real_escape_string($_POST["enamn"]);
$sql = "INSERT INTO tpersson (Perfnamn, Perenamn) VALUES ('$fname','$ename')";
$conn = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
Related
Whenever I tried to insert data to the table of database it keeps echoing "Connection successful" from connection.phpThe connection successful in my insert.php file
insert.php code
<?php
include_once("connection.php");
if(isset($_POST['Add'])){
$productCat = $_POST['category'];
$insertQuery = $pdo->prepare("INSERT INTO products_tbl (productCategory) VALUES (:ucategory)");
$insertQuery->bindParam(':ucategory',$productCat);
$insertQuery->execute();
echo "<script>alert('Successfully Register')</script>";
echo "<script>window.open('index.php','_self')</script>";
}
?>
connection code
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "Ecommercedb";
try{
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection success";
} catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
?>
forms
<form action="insert.php" method="post">
<label for="">Product Category</label>
<input type="text" name="category" id="" placeholder="Category">
<input type="submit" value="Submit" class="btn" name="Add">
</form>
I tried removing the echo enter image description heresince it wasn't needed but it only lead to
HTTP:500 error.
I have also checked the connection and it is successful.
I expected there would be an alert saying it is successfully inserted but instead I keep getting the connection success from my connection.php
It looks like your code is working as intended, and the issue is likely related to the way you are submitting your form. The "Connection successful" message is being printed because your connection to the database is working, but the form data is not being passed to the insert.php script.
Make sure that you are correctly specifying the action attribute of the form element, and that the method is set to "post". Also, check that the name attributes of the form elements match the names of the variables in the insert.php script.
Additionally, you can try adding some debugging statements to the insert.php script, such as var_dump($_POST) or echo $productCat to check if the values are being passed to the script correctly.
I'm a novice at mysql having trouble with inserting fields. I have created a login form and a homepage form for users to enter personal details. The login form submitted to mysql database fine, but the personal details form refused to submit; only when I specified the same fields as the first form did the form submit. Obviously, I would like to add new data in the second form, and I would appreciate tips on organizing my database, which consists of a single table profile.It stores info on every user including fields: id,username,password,avatar,location,goal, etc.
Appreciate your help & patience. I will combine the info from the two forms into a user record eventually. Right now, though, I would like to know why no new entry is created or error message displayed even though my error display is turned on.
EDIT:: sorry for not including whole code
loginform.php (works fine)
<?php
require("connect.php");
session_start();
$query = "SELECT * FROM `profile`";
if ($query_run=mysqli_query($cnn,$query))
{
echo "
<h1>Sign up for Runners World</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Email: <input type='text' name='email'><br>
Password: <input type='text' name='pw'><br>
<input type='submit' name='submit' value='submit'>
</form>
";
}
else {
die("<br>could not connect to table");
}
?>
<?php
if (isset($_POST['submit']))//if you submitted the form
{
$username = $_POST['username'];
$password = $_POST['pw'];
$email = $_POST['email'];
if ($username and $password and $email)
{
$addLogin = "INSERT INTO profile (username,email,password) VALUES ('$username','$email','$password')";
$success = $cnn->query($addLogin);
if ($success)
{
$_SESSION['name']="$username";
echo("<script>location.href = 'homePage.php';</script>");
}
else
{
die("login data failed to reach database");
}
}
else {echo "please fill out all the fields";}
}
else {
$submit=null;
echo 'no form submitted';
}
?>
addDetails.php (not submitting)
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors",1);
require("connect.php");
require("login.php");
echo "<h1>Welcome ".$_SESSION['name']."</h1>";
echo "<form action='' method='post'>
Avatar: <input type='text' name='avatar'><br>
Location: <input type='text' name='location'><br>
Descripiton: <input type='text' name='about'><br>
Daily Goal: <input type='text' name='goal'><br>
<input type='submit' value='submit' name='submit'>
</form>
";
$avatar = $_POST['avatar'];
$location = $_POST['location'];
$goal = $_POST['goal'];
$about = $_POST['about'];
if (isset($_POST['submit']))
{
$sql = "INSERT INTO profile (avatar,location,goal) VALUES ('$avatar','$location','$goal')";
if ($cnn->query($sql)===TRUE)
{echo "you have inserted profile fields";}
else
{echo "sqlQuery failed to insert fields";}
}
?>
If you want to add data to a row that already exists, look up the UPDATE command in SQL
You should change the Sql statement in 'addDetails.php' to:
UPDATE profile
SET avatar={$avatar}, location={$location}, goal={$goal}
WHERE id={$id}
By the way you should never ever use this statement in your production, it is not safe, you should keep in mind to prevent Sql injection.
I have searched for answers regarding this but to no avail so far. First off I am developing a Quiz Application, and yes I have to use php and MySQL I don't have a choice. The user enters his/her name into the text box on the login page and the username is stored in a database of names.
Then the database retrieves questions and answers from the database. I know it has something to do with the form action attribute because when I leave it blank it works fine, but otherwise it does not store values. So really I am wondering how I can pass info to a database and at the same time bring the user to another page of my choosing (without opening a new tab).
Any help would be greatly appreciated and I will try to format my code as well as I can. I am new to this so I understand it will be messy and ugly, sorry in advance.
<DOCTYPE html>
<html>
<head>
<title>Entrance Page</title>
</head>
<body>
<h1>Welcome to our Quiz App V1 Alpha</h1>
<p>Please select which quiz you would like to take, you will take all 10
questions and at the end you can see how you stack up against everyone
else. Please enter your name below.</p><br />
<!-- This form will take in an entered username and put it into a database,
if it is already in the database then they will be asked to take a new test,
but they cannot retake an old one -->
<form action="HytecCampQuestionPage.php" method="POST">
<p>Username:
<input type="text" name="name" id="name">
<input type="submit" value="Submit">
<?php
include 'HytecFunctions.php';
if((isset($_POST["name"])) ) {
$name = $_POST["name"];
addName($name);
}
else {
echo "It didn't work";
}
?>
</form>
</body>
</html>
<DOCTYPE html>
<html>
<head>
<title>Question Page</title>
</head>
<body>
<?php
include 'HytecFunctions.php';
$questionNumber = 1;
while ($questionNumber <= 10) {
showQuestion($questionNumber);
$questionNumber++;
}
?>
</body>
</html>
<?php
function connectDB() {
$servername = "localhost";
$username = "root";
$password = "C1e2r3n4y5f629#";
$dbname = "QuizApp";
//Create a connection object and return it to the caller
$conn = new mysqli($servername, $username,
$password, $dbname);
if ($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
function addName($name) {
$conn = connectDB();
//Insert into the QuizApp table the element with the passed information
$sql = $conn->prepare("INSERT INTO Names (Name, Score)
VALUES(?, 0)");
// Puts values into above ?s
$sql->bind_param("s", $name);
$sql->execute();
$sql->close();
$conn->close();
}
function showQuestion($number) {
$conn = connectDB();
//Select everything from the Question table and print it to the screen within <radio tags>
$sql = $conn->prepare("SELECT id, question, a, b, c, d, answer FROM Question WHERE id=$number");
$sql->execute();
$sql->bind_result($id, $question, $a, $b, $c, $d, $answer);
while($sql->fetch()) {
echo "<h1>Question $id </h1>";
echo "<p>$question</p>";
echo "<form>
<input type=\"radio\" name=\"answer\" value=\"a\">$a<br>
<input type=\"radio\" name=\"answer\" value=\"b\">$b<br>
<input type=\"radio\" name=\"answer\" value=\"c\">$c<br>
<input type=\"radio\" name=\"answer\" value=\"d\">$d<br>
<input type=\"submit\" name=\"Submit\">
</form>";
echo "Login Page ";
}
$sql->close();
$conn->close();
}
?>
I am currently learning SQL and have created this code for a few hours but I am unable to add data to my SQL server. Below I have provided a minimum working example of an input field and submit to SQL server. Any help is greatly appreciated. (I removed the password). I believe the problem is with isset($_POST['submit'] or before this point as the server does not seem to acknowledge the rest.
With thanks!
<html>
<body>
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
<?php
// Setting up the Database Connection
$username = "root";
$password = "";
$dbname = "table_name";
$link = mysqli_connect('localhost', $username, $password);
#mysqli_select_db($dbname);
if(isset($_POST['submit']))
{
$field = isset ($_POST['field']);
$field_f = mysql_real_escape_string($field);
$que = "INSERT INTO table_test ('fieldsql') VALUES ('$field_f')";
mysqli_query($que);
if (mysqli_query($link,$que) === TRUE) {
echo "Record added successfully";
}}
mysqli_close($link);
?>
</body>
</html>
You are missing form in your html. Without form tag your textarea and submit button wont work.
Try this :
<html>
<body>
<form method="post">
<table class="dd" width="100%" id="data">
<td>Field</td>
<td>:</td>
<td width="17%"><input type='textarea' name='field'/></td>
</table>
<input name='submit' type='submit' value='submit'/>
</form>
Also your query is wrong. Please use following query :
"INSERT INTO table_test (fieldsql) VALUES ('$field_f')";
Side note : Your query is unsafe. Read this
How can I prevent SQL injection in PHP?.
I have two different directories on my wampserver, this code works on one, but not on the other, I don't understand why.
PHP
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$msg = "";
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUE ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
$msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
HTML
<form method="post" action="add_class.php">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
This is in the file "add_class.php" and I've tried many different things, putting single quotes (`) around the table columns in the $sql but still, it won't work. I've tried adjusting the names in the table, which had underscores but now have camelCasing, still made no difference. This code works perfectly in another directory, can someone please tell me why this is happening and possibly propose a solution? Thank you in advance.
P.S My connection works because I inserted a new row via phpmyadmin and looped through the database printing every existing "className" and it worked, I just can't insert from the php script.
connection.php
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
When asked if you've had assigned the sessions, you replied I assigned this when the user logs in. Moving forward from that, let's assume the assigned session as one written below:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
$_SESSION['username'] = "HawqasKaPujaari";
$msg = "";
// this fails, as session is already set.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
die();
}
if(isset($_SESSION['username'])) {
if (isset($_POST['submit']))
{
$className = $_POST['className'];
$classColour = $_POST['classColour'];
include_once("connection.php");
$sql = "INSERT INTO class (className, classColour) VALUES ('$className', '$classColour')";
mysqli_query($dbConnection, $sql);
echo $msg = "New class '" . $className . "' added.";
} else {
$msg = "No class added yet.";
}
}
?>
<form method="post" action="">
<input type="text" name="className" placeholder="Class" />
<input type="text" name="classColour" placeholder="Colour" />
<div><input type="submit" name="submit" value="Add" class="btn butn-orange"/></div>
</form>
Note: The only changes I made were to change the action="" empty and changed VALUE to VALUES in your query.
connection.php:
<?php
$dbConnection = mysqli_connect("localhost","root", "", "main");
if(mysqli_connect_errno())
{
echo "Failed to connect" . mysqli_connect_error();
}
?>
As the above posted code seemed to be correct and was bugging me so I thought of testing it myself by creating the database/tables and it seemed to work properly without any errors. I have posted the relevant pictures below:
Note: Make sure you have the connection.php file in the same
directory as the add_class.php.