PHP MySQL Error echo insert into values printing on screen - php

I am learning PHP MYSql and faced an error while writing a marks submission program. When i run the program in chrome, the table is coming ok but neither the values are inserting in the MySQL table nor the redirection to different webpage taking place. You will understand it more clearly in the code and screen given below
<html>
<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$connection = mysql_connect("localhost","root","");
if($connection == false)
{
echo("<h3>Unable MySQL</h3>");
die();
}
$db = mysql_select_db("IGNOU",$connection);
if($db == false)
die("<h3>Unable to connect to DB</h3>");
if(isset($_POST['submit']))
{
$rcptno=mysql_real_escape_string($_POST['rcptno']);
$subdt=mysql_real_escape_string($_POST['subdt']);
$amarks=mysql_real_escape_string($_POST['amarks']);
$Vvmarks=mysql_real_escape_string($_POST['Vvmarks']);
$chk_dt=mysql_real_escape_string($_POST['chk_dt']);
$roll_no=mysql_real_escape_string($_POST['roll_no']);
$sbcode=mysql_real_escape_string($_POST['sbcode']);
$ecode=mysql_real_escape_string($_POST['ecode']);
$query1=mysql_query("insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt',
'$roll_no','$sbcode','$ecode')");
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
if($query1)
{
header("location:studentmaster.php");
}
}
?>
<fieldset style="width:400px;">
<form method="post" action="">
Reciept No.: <input type="number" name="rcptno" min="1">
<br>
Submission Date.: <input type="date" name="subdt">
<br>
Assignment Marks: <input type="number" name="amarks" max = "100">
<br>
Viva Marks: <input type="number" name="Vvmarks" max="100">
<br>
Checking Date.: <input type="date" name="chk_dt">
<br>
Roll No.: <input type="text" name="roll_no">
<br>
Subject Code.:
<input type="text" name="sbcode">
<br>
Evaluator Code:
<input type="text" name="ecode">
<br>
<input type="submit" name="submit">
</form>
</fieldset>
</body>
</html>
Screen
[This is the screen in which i have not yet clicked submit button]
[Now i have Clicked Submit button but it only displays a line...no insertion...no redirection]
Kindly help in overcoming this problem....

You're seeing the output because your using this line.
echo "insert into assignment values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt','$roll_no'
,'$sbcode','$ecode')";
Also you need to make sure that you have successfully inserted or not.
For this you should use these lines of code.
if ($query1) {
header('Location: studentmaster.php');
} else {
echo 'No redirect means query failed';
var_dump(mysql_error($connection));
}
Because you're learning you can skip mysql_* functions and move to mysqli, PDO

Just replace the insert query with this
insert into assignment(`col1`,`col2`,`col3`,`col4`,`col5`, `col6`,`col7`,`col8`) values('$rcptno','$subdt','$amarks','$Vvmarks','$chk_dt', '$roll_no','$sbcode','$ecode')
replace col1, col2, col3... with your mysql table columns

Related

Not able to insert data using html form and php using wamp [duplicate]

This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 1 year ago.
I am trying to insert data into a database from HTML form using php. I made two files html form and other is PHP script. When I click on submit in html form, it shows me the php code. I am using wamp server for database. I put my html files in C:/wamp64/www directory and html files at my local directory. The database table is :
id int(11)
fname varchar(30)
salary int(11) . Id is not auto-incremented and it is a primary key.
Html code:
<html>
<body>
<h2>Employee's Information</h2>
<form action="employee.php" method="POST">
<label for="id">Enter employee id:</label><br>
<input type="text" id="id" name="id" value=""><br>
<label for="fname">Enter First name:</label><br>
<input type="text" id="fname" name="fname" value=""><br><br>
<label for="salary">Enter Employee Salary:</label><br>
<input type="text" id="salary" name="salary" value=""><br><br>
<input type="submit" id="submit" name="submit" value="Submit">
</form>
</body>
</html>
Php code:
<?php
$mysql_hostname="localhost";
$mysql_username="root";
$mysql_password="";
$mysql_database="employee";
$con=mysql_connect($mysql_hostname,$mysql_username,$mysql_password);
if(!$con){
die('Connection Error: '.mysql_error());
}
mysql_select_db($mysql_database, $con);
if(isset($_POST['submit']))
{
$s_id = $_POST['id'];
$s_name = $_POST['fname'];
$salary = $_POST['salary'];
$employeeinsert = "INSERT INTO employee1
(id, fname, salary)
VALUES('".$s_id."','".$s_name."','".$salary."')";
if(!mysql_query($employeeinsert,$con)) {
echo "Error: " .mysql_error($con);
} else {
echo "1 record added";
}
}
?>
The code is neither giving any error on submitting data nor it is inserting the data into the database.
I am not getting what the error is.
If this is false then the code successfully produces no output:
if(isset($_POST['submit']))
Which is what's happening, since the condition is false. The form has a submit button, but that button has no name attribute to its value isn't sent to the server:
<input type="submit" value="Submit">
Give it a name:
<input type="submit" name="submit" value="Submit">
It's always a good idea to have some kind of indication of any given code branch, even if just logging something somewhere so you can see what's happening. Code will happily produce no output/result if that's what it's instructed to do, but as you've discovered it can leave you with no information about what's happened.
As an aside, and this is important, your code is wide open to SQL injection. You'll want to start addressing that.

Form Data Gets Inserted Into MySQL Table But Still Server Throws Error

I want to insert some values into my book table and I created a PHP page with HTML form inside it. The problem is my values gets inserted but it throws a primary key error on the webpage. The code is as below.
<!DOCTYPE html>
<html>
<head>
<title>New Books</title>
</head>
<body>
<?php
if (isset($_POST['submit'])) {
$server="localhost";
$username="root";
$password="";
$db="library";
$conn= new mysqli($server,$username,$password,$db);
if ($conn->connect_error) {
echo "Server Error Occured Please Try Again Later";
}
$bid=$_POST['bid'];
$bname=$_POST['bname'];
$baut=$_POST['baut'];
$bc=$_POST['bc'];
$blf=$_POST['blf'];
$bs=$_POST['bs'];
$sql="insert into books(BOOK_ID,BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE, BOOK_STATUS) values('$bid','$bname','$baut','$bc','$blf','$bs')";
$result=$conn->query($sql);
if ($conn->query($sql)===TRUE) {
echo "New Book Added Successfully";
}
else{
echo "Please Recheck The Values Entered" . $conn->error;
$secondsWait = 5;
header("Refresh:$secondsWait");
}
}
?>
<div class="header">
Lowa State University
<div class="header-right">
<a class="active" href="#">Main Page</a>
Due Fines
Contact Us
Profile
</div>
</div>
<form action="" method="post">
<input type="text" name="bid" placeholder="BOOK ID"><br><br>
<input type="text" name="bname" placeholder="BOOK NAME"><br><br>
<input type="text" name="baut" placeholder="BOOK AUTHOR"><br><br>
<input type="text" name="bc" placeholder="BOOK CATEGORY"><br><br>
<input type="number" name="blf" placeholder="BOOK LOST FINE"><br><br>
<input type="text" name="bs" placeholder="BOOK STATUS"><br><br>
<input type="submit" name="submit" value="Add Book"><br><br>
<input type="reset" name="reset" value="Clear Fields">
</form>
</body>
</html>
SAMPLE VALUES IN FORM
Now if I press the add button this error shows up:
Error Image:
but the values are already entered into the SQL table.
When you add any field as primary key that mean it must have unique record, no duplication allowed. you trying to add duplicate(same record) in same table.
You should add BOOK_ID as primary key + auto increment in database and when you insert new record, you don't need to add BOOK_ID manually at code. i automatically incremented from previous record and added automatically.
Just do like this
$sql="insert into
books(BOOK_NAME,BOOK_AUTHOR,BOOK_CATEGORY,BOOK_LOST_FINE,
BOOK_STATUS) values('$bname','$baut','$bc','$blf','$bs')";
and remove following line $result=$conn->query($sql);
Note [add BOOK_ID AS PRIMARY KEY + AUTO INCREMENT in Table]
Just like hingu Devang and Bira mentioned, make your ID column Auto_Increment and do not manually place a value there because it will automatically assign a value.
As for your issue that the query is being executed twice, try removing the line:
$result=$conn->query($sql);
Because you already have a query which is:
if($conn->query($sql)===TRUE)

getting data from a textarea into a database

i am trying to get text from a text box into my database, but it wont go through. i have tried so many things please help!! the else statement always executes, because I get the message "no submission received on my webpage", which means the first if statement definitely executes.
As FirstOne said you need to name the input "submit".
<input class="input" type="submit" name="submit" value="شارك"/>
Hello There are two problem's with your code ..
First one add name attr in your submit button because you are checking isset($_POST['submit'])
<input class="input" type="submit" name="submit" value="شارك"/>
Second Update Your $query with this
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('".$_POST["newSecret"]."',0)";
first of all you didn't give the submit button a name so you must name it 'submit' to match what you wrote in your code and also your SQL query seems to be incorrect, here's a snippet with the desired changes:
<form method="post" action="post.php">
<textarea name="newSecret" id="help" class="textarea" rows="20" cols="100">
</textarea>
<input class="input" name="submit" type="submit" value="شارك"/>
</form>
<?php
if(isset($_POST['submit'])) {
// trim possible begining/ending whitespaces from the the textarea value. But you still need to escape it againt SQL injection !
$newSecret = trim($_POST['newSecret']);
if(isset($newSecret)[0]) {
include "db_connect.php";
$query= "INSERT INTO hamsasubmissions (secret,popularity) VALUES ('" . $newSecret . "', 0)";
if(!mysqli_query($mysqli,$query)){
echo "no submission received";}
else{echo "Secret submitted.";}
}
}
?>

how to update mySQL database using a post method in php

i have created a leaderboard for a website which displays users high scores for a game. but whe the user goes to edit their high score, it doesnt change in the database or on the screen. does anybody know how to update the database using a post method. my code is below.
require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
//require_once('../sokodatabase.php');
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$query = "
UPDATE leaderboardhighscores
SET highScores=".$_POST["highScores"].", rankNo=".$_POST["rankNo"]."
WHERE userId=".$_POST["userId"];
var_dump($_POST);
echo $query;
#mysqli_query($dbc, $query);
}
}
$manager = new DatabaseManager;
$manager->SelectHighScores();
?>
<form method="post" action="highScores.php">
high score <input type="text" name="highScores"/>
rankNo <input type="text" name="rankNo"/>
userId <input type="text" name="userId"/>
<input type="submit" value="Submit">
</form>
You have to provide attention to SQL injections!
Normally, you check for the submit button:
<input type="submit" name="submit" value="Submit">
Then
if(isset($_POST['userId'])){
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
goes to:
if(isset($_POST['submit'])){
If your query does not work, you can make die($query) to see it and perform it via phpMyAdmin. Or you can use mysqli_error to display any occured error after executing it.
Please note, that with your code only numeric values are possible. If your fields are not numeric, you should use this:
$query = "
UPDATE leaderboardhighscores
SET highScores='".mysqli_real_escape_string($dbc, $_POST["highScores"])."', rankNo='".mysqli_real_escape_string($dbc, $_POST["rankNo"])."'
WHERE userId=".intval($_POST["userId"]);
Need name for the submit input type in-order to submit the form...
Like
<input type="submit" name="userId" value="Submit">
if(isset($_POST['userId']))

PHP Form with required fields

I want to creat a form which can connect to mysql and can insert records which I have done. But now I want to make some fields mandatory, username and car for example. Also showing the error field as required or "name cannot have numbers". Stuff like that. I am unable to figure it out.
Some help please:
I have index.html
<form action="insert.php" method="post">
Nume: <input type="text" name="name"><span class="error">* <?php echo $error;?></span><br>
Prenume: <input type="text" name="prenume"><br>
Masina: <input type="radio" name="masina" value="vito"> (Vito)
<input type="radio" name="masina" value="skoda"> (Skoda)
<input type="radio" name="masina" value="skoda2"> (Skoda)
<input type="radio" name="masina" value="audi"> (Audi)<br><br>
Data: <input type="date" name="data"/><br>
Ora: <input type="time" name="ora"/><br>
Destinatie:<input type="text" name="destinatie"><br>
KM la iesire: <input type="text" name="kmiesire"><br>
KM la intrare: <input type="text" name="kmintrare"><br>
<input type="submit">
and Insert.php
<?php
include "connect.php";
$order = "INSERT INTO data_employees
(name, prenume, masina, data, ora, destinatie, kmiesire, kmintrare)
VALUES
('$_POST[name]',
'$_POST[prenume]',
'$_POST[masina]','$_POST[data]','$_POST[ora]','$_POST[destinatie]',
'$_POST[kmiesire]','$_POST[kmintrare]'
)";
if (mysqli_query($con,$order)){
header('Location: index.html');
}else{
echo("Input data is fail");
}
?>
you have to check rules before the query...
if(empty($_POST['name'])){
echo "Name Required";
}
elseif(bla bla){
echo "something"
}
else {
// your query....
}
Start checking with ,
if($_POST) {
if(isset($_POST['name'])!='') {
echo 'your error message';
}else if (isset($_POST['prenume'])!='') {
echo 'your error message';
}.....
else
//your insertion code (query)
}
And also you can check with # ,empty like isset .
You have to check that POST values are not empty then there is no injected code to prevent injection attacks.
You should take a look to PDO PHP. It will be more safer than mysql low-level functions and more easy to use.

Categories