I'm trying to make a form that updates a datebase but it gives me two errors. Do you have any idea what it could be from?
The errors:
Notice: Undefined variable: Points inD:\2013.1\xampp\htdocs\ranklist_get.php on line 9
Notice: Undefined variable: Skype in D:\2013.1\xampp\htdocs\ranklist_get.php on line 9
welcome.html
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype"><br>
Points: <input type="number" id="Points"><br>
<input type="submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
mysqli_close($con);
?>
Initialize your variables with the expected values before you use them in your query.
$Points=mysqli_real_escape_string($con,$_GET["Points"]);
$Skype=mysqli_real_escape_string($con,$_GET["Skype"]);
Also make sure to add the name attribute to your form fields. name="Points" and name="Skype", otherwise it wont work.
GET variables are stored in the global $_GET array (just like POST and COOKIE). You can either use them directly in your code like so $_GET["Points"] or store them in a variable.
Please note you should use the name property on each input to specify it's key in the array.
At the top of your code put:
$Points = $_GET["Points"];
$Skype = $_GET["Skype"];
Your form should be rewritten like so:
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit">
</form>
You should also sanitize your MySQL query like so:
$query = mysqli->prepare($con, "UPDATE Persons SET Points=? WHERE Skype=?");
$query->bind_param('ss', $points, $skype);
$points = $_GET["Points"];
$skype = $_GET["Skype"];
$query->execute();
You can read more about prepared statements here: http://php.net/manual/en/mysqli.prepare.php
make HTML as
<html>
<body>
<form action="ranklist_get.php" method="get">
Skype: <input type="text" id="Skype" name="Skype"><br>
Points: <input type="number" id="Points" name="Points"><br>
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>
ranklist_get.php
<?php
$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if($_REQUEST['Submit']=='Submit'){
$Points=$_REQUEST['Points'];
$Skype=$_REQUEST['Skype'];
mysqli_query($con,"UPDATE Persons SET Points='".$Points."' WHERE Skype='".$Skype."'");
}
mysqli_close($con);
?>
You have to get the values before you use it.
Related
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.
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
<html>
<head>
</head>
<body>
<form action="mysql.php" method="post">
First Name: <input type="text" name="fname"></br>
last Name: <input type="text" name="lname">< </br>
What is your favrite subject <input type="text" name="subject"></input> </br>
Your Age : <input type="text" name="age"></input> </br>
<input type="submit" name="submit" ></input>
<input type="reset" name="rs"></input>
</form>
<?php
if (isset($_POST\['submit'\]) ){
$_sa = mysql_connect( "localhost","Ali","pakistan");
if (!$_sa){
die("can not caonnect".msql_error());
}
/* ----------- condition ----------------------
if (empty($_POST\[fname\])) {
echo "First name required";
}
------------------condition end ----------------- */
mysql_select_db("google", $_sa );
line 46-- $sql = "INSERT INTO info (firstname,lastname,subject,age) VALUES ('$_POST \[fname\]','$_POST \[lname\]','$_POST \[subject\]', '$_POST \[age\]'')";
mysql_query($sql,$_sa);
mysql_close($_sa);
}
?>][1]
// when I run my code its give me error of
Notice: Array to string conversion in C:\xampp\htdocs\mysql.php on
line 46
Try this:
$sql = "INSERT INTO info (firstname,lastname,subject,age) VALUES ('{$_POST ['fname']}','{$_POST ['lname']}','{$_POST ['subject']}', '{$_POST ['age']}')";
Explanation:
$_POST is an array
So, you need to take care of it while accessing
And, If arrays are accessed inside String, then we should use {}
For example: {$_POST['subject']}
There is an extra single quote written at the end.
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']))
I was wondering could u help me resolve my PHP problem.
I made a PHP script that writes data from form in new row.
But, when i run script it says
Undefined index: name
I am still beginner of PHP but i hope u will help me.
Thanks any way.
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "error". mysqli_connect_error();
}
$name=($_POST['name']);
echo "ime: ".$name;
?>
<form method="post" action="go.php">
FIrst name: <input type="text" name="name"/>
<input type="submit" value="send"?>
</form>
Put it inside this if statement
if (isset($_POST['submit'])) {
$name=($_POST['name']);
echo "ime: ".$name;
}
$_POST['name'] is not defined if you don't submit the form. So, try to type something into the textarea and click on "send": this error won't appear.
Otherwise, you can tell php to consider $_POST['name'] only if it's set, updating your code like this:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno())
{
echo "error". mysqli_connect_error();
}
if(isset($_POST['name'])){$name=($_POST['name']);
echo "ime: ".$name;}
?>
<form method="post" action="go.php">
FIrst name: <input type="text" name="name"/>
<input type="submit" value="send">
</form>