Can anyone tell me why I am getting an Undefined Index error on my code here.
I have used this setup using the if(isset) condition in other parts of my project after
researching my original Undefined Index errors and ISSET fixed my problems. But it is not working here for some reason and I cannot see why.
This form is POSTING the input:
<form action="addAlbum_Processed.php" method="POST">
<p>Enter artistID of Artist<input type="number" name="artist_id" maxlength="2" size="2"></p>
<p>Enter name of Album to be created<input type="text" name="album_name" size="20"></p>
<input type="submit" name="submit" value="submit"></form>
and this page is processing the form input and updating the albums table in my database:
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
?>
I cannot see where I am going wrong. Regards, TW
This is a tiny example of your problem:
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
You check whether a submit form field was posted before using the other fields. So far, so good. (I would check for the fields that were going to be used, but at least you're checking something.)
But then:
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
You use the fields anyway.
What's more...you don't keep from trying to insert stuff if a form isn't being posted. So any time some rogue spider visits your page, you end up with a blank album in your database.
And that's not even mentioning the fact that you're still using mysql_query.
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
|__________________________| first
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
|_________________________| Repeated
you are fetching variables twice.only one that is if condition is enough.Also use isset for both the variables.
if(isset($_POST['submit']))
{
if isset($_POST['album_name'])
$album_name = $_POST['album_name'];
if isset($_POST['artist_id'])
$artist_id = $_POST['artist_id'];
}
Try something like in addalbam_process.php
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
if(isset($_POST['albam_name']){$album_name = $_POST['album_name']};
if(isset($_POST['artist_id']){$artist_id = $_POST['artist_id']};
}
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}','delete_marker = 0')";
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
mysql_close($connection);
Please, use MYSQLI or PDO to Prevent SQL INJECTION
here </form> is missing
and try something like this
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
}
A few things.
This line 'delete_marker = 0' should most probably read as
VALUES ('{$artist_id}','{$album_name}','0')
or VALUES ('{$artist_id}','{$album_name}',0)
As I read it 'delete_marker = 0' you are attempting to actually write this value inside the delete_marker column (ArtistID, Album, delete_marker)
Or, you're attempting to use a WHERE delete_marker = 0 clause, which can't be used in an INSERT INTO, but an UPDATE or SELECT rather.
And your if(isset($_POST['submit'])) conditional statement should be wrapping your entire code, instead of just your 2 form variables, because it's basically saying "Ok, assign these 2 variables, then ignore the rest if it's NOT set."
Plus, you're repeating those 2 input variables.
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
(I wrapped your entire code inside the if(isset($_POST['submit'])) conditional statement, btw.
Side note: If you're having a DB connection issue, use this instead:
$connection = mysql_connect('localhost', 'root', '');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
PHP Give this a try:
Sidenote: If this line fails VALUES ('{$artist_id}','{$album_name}', 0) put quotes around the 0 as in '0'
<?php
$connection = mysql_connect('localhost','root','')
or die(mysql_error());
echo "Connected to php Server <br>";
or die("Could not select assi2 database");
echo "Connected to assi2 database <br>";
if(isset($_POST['submit']))
{
$album_name = $_POST['album_name'];
$artist_id = $_POST['artist_id'];
$sqlQuery = "SELECT * FROM albums WHERE album = '{$album_name}'";
$result = mysql_query($sqlQuery, $connection) or die("Selection Query Failed !!!");
if (mysql_num_rows($result) != 0)
{
header ("Location: Album_Exists.html");
}
else
{
$sqlInsert = "INSERT INTO albums (ArtistID, Album, delete_marker)
VALUES ('{$artist_id}','{$album_name}', 0)"; // or add quotes around the zero
$result = mysql_query($sqlInsert, $connection) or die("Selection Query Failed !!!");
header ("Location: addAlbum_Processed.php");
}
} // closing brace for if(isset($_POST['submit']))
mysql_close($connection);
?>
Related
I have a form handler (I believe that is the correct terminology) called insert.php, this is used to post form data to a MySQL database on localhost. I have different tables each containing a single record and would like to choose which table the data goes to. I could duplicate the insert.php file for each table but that seems messy. How do I choose which table the data goes to via post?
current insert.php:
<?php
require_once 'login.php';
$con=mysqli_connect($hh,$un,$pw,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo 'Connected successfully';
$sql = "UPDATE PiBQ_Temp SET reqdTemp = '$_POST[setTemp]' WHERE tempKey = 1";
mysqli_query($con,$sql);
echo "1 record added";
header ('location: index.php');
mysql_close($con)
?>
What I think is needed for the $sql = variable:
$sql = "UPDATE '$_POST[myTable]' SET '$_POST[myField]' = '$_POST[myValue]' WHERE tableKey = 1"
My html is this:
<form action="insert.php" method="post">
<input type="text" name="myField" value="<?= $myValue ?>"/>
<input type="submit" value="Submit" />
what html should I be using to feed my revised insert.php file above, if that is correct? Thanks.
try this format
$sql = "UPDATE `".$_POST['myTable']."` SET `".$_POST['myField']."` = '".$_POST['myValue']."' WHERE `tableKey` = 1";
or
$mysqli = new mysqli("host", "user", "password", "db");
$stmt = $mysqli->prepare("UPDATE `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myTable'])))."` SET `".$mysqli->real_escape_string(str_replace(" ", "", strtolower($_POST['myField'])))."` = ? WHERE `tableKey` = 1");
$stmt->bind_param("s",$_POST['myValue']);
$stmt->execute();
You should use prepared statement instead
There's some wider practices that could be improve, but based on your current code/structure, I would use something like this:
<?php
require_once 'login.php';
try {
$con = new mysqli("host", "user", "password", "db");
} catch (mysqli_sql_exception $e) {
echo "Failed to connect to MySQL: ".$e;
}
$table = (isset($_POST['myTable'])) ? $_POST['myTable'] : null;
$reqdTemp = (isset($_POST['setTemp'])) ? $_POST['setTemp'] : null;
$tempKey = (isset($_POST['setKey'])) ? $_POST['setKey'] : null;
switch($table) {
case "thisTable":
$qry = "UPDATE `thisTable` SET thisField = ? WHERE thisKey = ?";
break;
case "thatTable":
$qry = "UPDATE `thatTable` SET thisField = ? WHERE thisKey = ?";
break;
case "anotherTable":
$qry = "UPDATE `anotherTable` SET thisField = ? WHERE thisKey = ?";
break;
default:
// do something?
break;
}
$stmt = $conn->prepare($qry);
$stmt->bind_param("si", $reqdTemp, $tempKey);
$stmt->execute();
if(!$stmt->execute()) {
echo $stmt->error;
}
else {
echo "1 record added";
}
header ('location: index.php');
mysql_close($con)
?>
Two things to note: The switch statement allows you to provide a different query based on the table name, but it assumes that the same structure is in place (i.e. update String Where Integer).
I've also assumed the thisKey is posted too, as 'setKey'.
Secondly, prepared statements.
This is more of a hint, rather than a whole solution, and you probably need to tidy it up and make it work for you outside of my assumptions
after I managed to connect my website form to my database, I decided to try to transfer over my files to my work computer.
Initially I only had one error: mysqli_fetch_row() expects parameter 1 to be mysqli_result, boolean given in...
However now I get an extra mysqli_fetch_row() error the same as above but the error is on a different line.
Additionally I also get the error: Undefined index: fill which I never got before. Are there any mistakes in my code? The form still works and can connect to my database.
<center><form action="fill.php" method="post">
Fill
<input type="text" id="fill"" name="fill">
<input type="submit" id ="submit" name="submit" value="Submit here!">
</form></center>
</div>
<?php
$val1 = $_POST['fill'];
$conn = mysqli_connect('localhost', 'root', '')or
die("Could not connect");
mysqli_select_db($conn, 'rfid');
$val2 = "SELECT * FROM card_refill WHERE refill = $val1";
$result1= $conn->query($val2);
$row = mysqli_fetch_row($result1);
$refill1 = $row[2];
$value = "SELECT *FROM card_credit ORDER BY id DESC LIMIT 1:";
$result = $conn->query($value);
$row = mysqli_fetch_row($result);
$refill = $row[2];
$money= $refill+$refill1;
echo $money;
$sql = "UPDATE card_credit SET value = '$money'";
if ($conn->query($sql) === TRUE) {
echo "Success";
}
else {
echo "Warning: " . $sql . "<br>" . $conn->error;
}
mysqli_close($conn);
?>
</body>
</html>
You're getting that error because you use $_POST['fill'] without checking whether it's set first. It will only be set when the form is submitted, not when the form is first displayed. You need to put all the code that processes the form input into:
if (isset($_POST['submit'])) {
...
}
BTW, you can do that entire update in a single query.
UPDATE card_credit AS cc
CROSS JOIN card_refill AS cr
CROSS JOIN (SELECT * FROM card_credit ORDER BY id DESC LIMIT 1) AS cc1
SET cc.value = cr.col2 + cc1.col2
WHERE cr.refill = '$val1'
Like GolezTrol said from his comment. You're mixing object and functional notation.
Although this might not work exactly how you need it to because I don't have all the information. I have written you something I think is close to what you're looking for.
<?php
// Define the below connections via $username = ""; EXTRA....
// This is best done in a separate file.
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$val1 = $_POST['fill'];
$result1 = $conn->query("SELECT * FROM card_refill WHERE refill = '$val1' ");
$result2 = $conn->query("SELECT * FROM card_credit ORDER BY id DESC LIMIT 1:");
$refill1 = array(); // Pass Results1 Into Array
while($row = $result1->fetch_assoc()) {
$refill1[] = $row[2];
}
$refill = array(); // Pass Results2 Into Array
while($row = $result2->fetch_assoc()) {
$refill[] = $row[2];
}
/* Without an example of what data you are getting from your tables you will have to figure out what data you want from the arrays.
$money= $refill+$refill1;
echo "DEBUG: $money";
*/
// This code will not be functional until your populate the $money value.
$sql = "UPDATE card_credit SET value = '$money' ";
if ($conn->query($sql) === TRUE) {
echo nl2br("Record updated successfully"); // DEBUG
print_r(array_values($refill1)); // DEBUG
print_r(array_values($refill)); // DEBUG
echo nl2br("\n"); // DEBUG
} else { // DEBUG
echo "Error updating record: " . $conn->error; // DEBUG
echo nl2br("\n"); // DEBUG
}
$conn->close();
?>
I have 2 PHP pages to delete employee data from table. For that, user inserts employee id, and press delete, to delete data from table.
Now, problem is, whenever I inserts id of one digit(2,3,8 etc), id is not deleted. However, if two digit id is inserted (12,19,99 etc), it gets deleted.
Please help me to solve where I am wrong.
Here is my code for first PHP page:
<form action="deleteemp.php" method="post" onSubmit="return confirm('Are you sure to delete?')">
Enter id to delete data<input type="text" name="EmpId" required>
<button type="submit" >Delete</button>
</form>
Here is my action PHP page,
<?php
$EmpId = $_POST['EmpId'];
$connection = mysql_connect("localhost", "root", "");
if (!$connection) {
die("Connection failed " . mysql_error());
}
$db_conn = mysql_select_db("hms", $connection);
if (!$db_conn) {
die("Connection failed " . mysql_error());
}
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
$db_result = mysql_query($query, $connection);
if ($db_result) {
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
} else {
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
echo "data not here" is incorrect. mysql_query returns boolean false on FAILURE. An empty result (no matching IDs) is NOT a failure. It's a successful query which happens to have an empty result set.
Your code should be more like
$result = mysql_query($query) or die(mysql_error());
if (mysql_affected_rows($result) == 0) {
die("No rows deleted");
}
And note that you are vulnerable to sql injection attacks, and using an obsolete/deprecated DB library.
Try this
$query = "DELETE FROM employee_details WHERE emp_id = '$EmpId'";
$db_result = mysql_query($query, $connection);
if ($db_result)
{
echo "Data Deleted Successfully !";
echo "<br>";
echo "<a href='homepage.php'>Back to homepage</a>";
}
else
{
echo "Data Not there. Try Again !<br>";
echo "<a href='deleteemp1.php'>Search again</a>";
}
This seems some exceptional issue, so try typecasting before passing value to SQL query.
Try using this for assigning value to $EmpId:
$EmpId = (int) $_POST['EmpId'];
can you try to change below code from
$query = "DELETE FROM employee_details WHERE emp_id = " . $EmpId;
TO
$query = "DELETE FROM employee_details WHERE emp_id =".$EmpId;
Just try. This might work for you
Login.php
session_start();
<?php
$username = "root";
$password = "tiger";
$hostname = "localhost";
//connection to the database
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
//select a database to work with
/* #var $selected type */
$selected = mysqli_select_db($dbhandle,"sample")
or die("Could not select sample");
$name=(\filter_input(\INPUT_POST,'name'));
$phone=(\filter_input(\INPUT_POST,'phone'));
$email=(\filter_input(\INPUT_POST,'email'));
//$custno=(\filter_input(\INPUT_POST,'custno'));
if(!empty(\filter_input(\INPUT_POST,'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql="insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result=mysqli_query($dbhandle,$sql) or die(\mysqli_error($dbhandle));
}
else
{
$sql1="insert into customersignin(custno)values(NULL)";
$result1=mysqli_query($dbhandle,$sql1) or die(\mysqli_error($dbhandle));
}
$sql2="select custno from customersignin";
$result2=mysqli_query($dbhandle,$sql2) or die (mysqli_error($dbhandle));
$row= mysqli_fetch_array($result2);
if(mysqli_num_rows($result2)>0)
{
echo "$_SESSION['custno']";
unset($_SESSION['custno'];
header('Location:customersvsoup.php');
}
mysqli_close($dbhandle);
$_SESSION[name]=(\filter_input(INPUT_POST,'name'));
customer.php
<body>
<?php session_start(); ?>
<input type="text" style="position: absolute;top:200px;" value="<?php echo $_SESSION["custno"]?>">
</body>
In the php file the customer log in is done,the custno is the auto generate field,i have 2 buttons called continue and skip,for both the auto generate works fine,after any of the button action is done,i need to display the custno in the text box of the next page using session.But the problem is the text box is empty when i run this code.But the session['name'] is working..Please help.
Your session_start(); should come at the beginning of the file in login.php. I see you using $_SESSION[custno] before it's called. That's why your textbox is empty.
Also it should be:
$_SESSION['custno']
$_SESSION['name']note the single quotes
Regarding your logical problem (in the comments) try:
$_SESSION['name'] = (filter_input(INPUT_POST, 'name'));
if (!empty(filter_input(INPUT_POST, 'continue')))
{
echo "<script type='text/javascript'>\n";
'check()';
echo "</script>";
$sql = "insert into customersignin(name,phone,email)values('$name','$phone','$email')";
$result = mysqli_query($dbhandle, $sql) or die(mysqli_error($dbhandle));
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
else
{
$sql1 = "insert into customersignin(custno)values(NULL)";
$result1 = mysqli_query($dbhandle, $sql1) or die(mysqli_error($dbhandle));
//since this bit of code is repeating,
//you could even use a function to shorten it
$sql2 = "select max(custno) as last_custno from customersignin";
$result2 = mysqli_query($dbhandle, $sql2) or die(mysqli_error($dbhandle));
if (mysqli_num_rows($result2) > 0)
{
$row = mysqli_fetch_assoc($result2);
$_SESSION['custno'] = $row['last_custno'];
header('Location:customersvsoup.php');
}
}
And please put the session_start(); inside after <?php. All php code should be within the PHP tags.
you have error in insert query:
$sql="insertintocustomersignin(name,phone,email)values('$name','$phone','$email')";
should be :
$sql="insert into customersignin(name,phone,email) values ('$name','$phone','$email')";
you should use quotes in array index :
$_SESSION[custno], $_SESSION[name] should be $_SESSION['custno'], $_SESSION['name']
I've created a text posting website. Except the posting on the post.php page I want to enable users to post text when they type www.mywebsite.com/post.php?name=MyName&body=MyText? How can I make this?
The post code looks like this:
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_POST['post'])
{
//get data
$title = $_POST['title'];
$body = $_POST['body'];
//check for existance
if ($title&&$body)
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
You will want to use $_GET not POST for the data from the query string.
//get data
$title = $_GET['title']; // or name if it's name
$body = $_GET['body'];
Try to use $_REQUEST - it has all the data you have posted to the script (from $_GET, $_POST and $_COOKIE global arrays)
First suggestion is, avoid direct queries based on query strings at all possible costs! This is a huge security concern.
Also, the code you supplied would is open to numerous security holes and concerns.
Anytime you call a variable via $_COOKIE, $_POST or $_GET and it is used in a query, use MySQLI/PDO Prepared statements when possible, or at least mysql_real_escape_string. This will attempt to sanitize the data going into your database.
Also, You are GETTING parameters from the the url/query string, change POST to GET.
Additionally, your line which says:
if($_GET['post'])
Will always fail, you do not have a parameter in your url called post. For that to work, it would need to look like:
post.php?post&name=MyName&body=MyText?)
See below:
<?php
//insert category to database
// makes sure qty is numeric # added by sixeightzero
if(isset($_GET['qty']) && is_numeric($_GET['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_GET['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query(mysql_real_escape_string($sql));
// sanitizes input # added by sixeightzero
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if (!isset($_GET['name']) && !isset($_GET['body'])){
//get data
$title = $_GET['name'];
$body = $_GET['body'];
//check for existance
if ($title && $body)
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','".mysql_real_escape_string($title)."','".mysql_real_escape_string($body)."','".mysql_real_escape_string($date)."')") or die(mysql_error());
// sanitizes input # added by sixeightzero
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
Here's the complete source code!!
Try using this
<?php
//insert category to database
if(isset($_POST['qty'])) {
// Fetch and clean the <select> value.
// The (int) makes sure the value is really a integer.
$qty = (int)$_POST['qty'];
// Create the INSERT query.
$sql = "INSERT INTO `table`(`quantity`)
VALUES ({$qty})";
// Connect to a database and execute the query.
$dbLink = mysql_connect('MyServer', 'username', 'password') or die(mysql_error());
mysql_select_db('database_name', $dbLink) or die(mysql_errno());
$result = mysql_query($sql);
// Check the results and print the appropriate message.
if($result) {
echo "Record successfully inserted!";
}
else {
echo "Record not inserted! (". mysql_error() .")";
}
}
if ($_SERVER['REQUEST_METHOD'] == "GET") //check whether its a GET method
{
//get data, since you know that a valid "GET" request was sent
$title = $_REQUEST['title'];
$body = $_REQUEST['body'];
if (isset($title) && isset($body)) //check for existance
{
mysql_connect("MyServer","username","password") or die(mysql_error());
mysql_select_db("database_name") or die(mysql_error());
$date = date("Y-m-d");
//insert data
$insert = mysql_query("INSERT INTO news VALUES ('','$title','$body','$date')") or die(mysql_error());
die("Your text has been posted!");
}
else
echo "Please fill out your name and text";
}
?>
$_REQUEST is basically the result of array_merge($_GET,$_POST,$_COOKIE), so you can use it to get a value which may be a GET or POST variable.