This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
I followed a youtube tutorial which teaches you how to create an edit and delete data page for PHP and MYSQL but for some reason why code isn't working. Two error messages showed up:
Notice: Undefined variable: _Get in C:\Users\siaw_\PhpstormProjects\Report Page\modify.php on line 6
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\Users\siaw_\PhpstormProjects\Report Page\modify.php on line 8
I followed the tutorial exactly the way it is... I have very limited knowledge on PHP & MYSQL so please figure out the error on line 6 and 8?
Here is the code:
<?php
include 'connect.php';
if(!isset($_POST['submit'])) {
$q = "SELECT * FROM people WHERE ID = $_Get[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
?>
<h1>You Are Modifying A User</h1>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name <input type="text" name="inputName" value="<?php echo $person['Name']; ?>" /><br />
Description <input type="text" name="inputDesc" value="<?php echo $person['Description']; ?>" />
<br />
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>" />
<input type="submit" name="submit" value="Modify" />
</form>
<?php
if(isset($_POST['submit'])) {
$u = "UPDATE people SET `Name`='$_POST[inputName]', `Description`='$_POST[inputDesc]' WHERE ID = $_POST[id]";
mysql_query($u) or die(mysql_error());
echo "User Has Been Modified";
header("Location: index.php");
}
?>
Also here is the youtube link which I used (https://www.youtube.com/watch?v=kc1bppUlqps)
You should bind properly the variables into your query
You should also sanitize your variables before using them into your query by using *_real_escape_string()
I think your page will have an error when the first isset($_POST["submit"]) condition was not met.
Sanitize your variable(s) first:
$id = mysql_real_escape_string((int) $_GET["id"]);
Bind them to your query:
$q = "SELECT * FROM people WHERE ID = '$id'";
Note that mysql_* is already deprecated and you should consider at least the mysqli_*.
But...mysql is deprecated :(
If you are interested with mysqli_*, you can check this:
First, we have to connect to your database (connection.php) using mysqli_*:
$conn = new mysqli("Host", "Username", "Password", "Database"); /* REPLACE NECESSARY DATA */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Then for your php file where you process the $_GET["id"]:
if(isset($_POST['submit'])) {
$stmt = $con->prepare("SELECT Name, Description FROM people WHERE ID = ?"); /* PREPARE THE QUERY */
$stmt->bind_param("i", $_GET["id"]); /* BIND $_GET["id"] TO YOUR QUERY; i STANDS FOR INTEGER TYPE */
$stmt->execute(); /* EXECUTE YOUR PREPARED QUERY */
$stmt->bind_result($name, $description); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
$stmt->fetch(); /* FETCH THE RESULTS */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
/* YOUR HTML CODE HERE */
if(isset($_POST['submit'])) {
$stmt = $con->prepare("UPDATE people SET Name = ?, Description = ? WHERE ID = ?");
$stmt->bind_param("ssi", $_POST["inputName"], $_POST["inputDesc"], $_POST["id"]); /* s STANDS FOR STRING TYPE */
$stmt->execute();
$stmt->close();
echo "User Has Been Modified";
header("Location: index.php");
}
You need to put the $_GET outside, and also your $_GET syntax is incorrect, try to change :
if(!isset($_POST['submit'])) {
$q = "SELECT * FROM people WHERE ID = $_Get[id]";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
with this one :
if(!isset($_POST['submit'])) {
$id = $_GET['id'];
$q = "SELECT * FROM people WHERE ID = $id";
$result = mysql_query($q);
$person = mysql_fetch_array($result);
}
Related
<html>
<body>
<form action="checkorderstatus.php" method="post">
<input id="search" type="text" placeholder="Type here">
<input id="submit" type="submit" value="Search">
</form>
</body>
</html>
<?php
require_once 'loginorder.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) {
die($conn->connect_error);
}
if (isset($_POST['submit']));
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = $conn->query($query); //run the query and get the result
if (!$result) {
die($conn->error);
}
$rows = $result->num_rows;
$query = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid LIKE '%$search%'";
$result = mysqli_query($conn, $query);
($row = mysqli_fetch_row($result)); {
echo $row['1'];
print_r($row);
}
?>
I'm trying to display the status description when the statusid is entered into the search but it's not displaying anything other than Array ( [0] => product is in transit )
and I'm getting 3 errors
Notice: Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 20 Notice:
Undefined variable: search in
C:\wamp64\www\groupproject\checkorderstatus.php on line 28 Notice:
Undefined offset: 1 in C:\wamp64\www\groupproject\checkorderstatus.php
on line 36
Problems
There are a host of problems with your code as it stands...
Forms posted to PHP use the name attribute in the $_POST superglobal
Therefore you are effectively not submitting anything when you submit your form
Add the name="..." attribute to each of your form elements to fix this
Your if statements are by and large redundant
Not least because you don't post anything as per point 1
You should be using prepared statements for user generated input to protect your database from attack and or corruption
Your code is generally confusing and not laid out very well
I'm not sure what half of your brackets, ifs and function calls are supposed to be doing
The notice you're getting is because you never set $search in your PHP
Solution
N.B
This assumes that all of the code is in the one file [`checkorderstatus.php] and that it submits to itself.
Additional note:
I'm not sure that LIKE '%...% is the best solution here. It appears you're looking for id which, presumably (?) is a number? In which case I would simply user:
WHERE deliverystatus.statusid = SEARCH_ID
The below code follows that premise. If however you are indeed in need of LIKE then you should update the query like:
WHERE deliverystatus.statusid LIKE ?
and update the search term in the code:
$search = "%".$_POST["search"]."%";
Updated HTML form
<form action="checkorderstatus.php" method="post">
<input id="search" name="search" type="text" placeholder="Type here">
<input id="submit" name="submit" type="submit" value="Search">
</form>
Using mysqli
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli ($hn, $un, $pw, $db);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $mysqli->prepare($sql); // Prepare the statement
$query->bind_param("i", $search); // Bind search valus as an integer (use "s" if it's a string)
$query->execute(); // Execute the query
$query->store_result(); // Store the result
$query->bind_result($status_description); // Bind "statusdescription" to a varaible
while($query->fetch()){ // Loop through result set
echo $status_description}."<br>"; // Echo each match to a newline
}
}
Using PDO
$pdo = new pdo(
"mysql:host={$hn};dbname={$db}", $un, $pw,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => FALSE
]
);
if(isset($_POST["submit"])){
$search = $_POST["search"]; // Prepare the search term
$sql = "SELECT statusdescription FROM deliverystatus WHERE deliverystatus.statusid = ?";
$query = $pdo->prepare($sql); // Prepare the statement
$query->execute([$search]); // Execute the query binding search as the parameter
while($result = $query->fetchObject()){ // Loop through result set
echo $result->statusddescription."<br>"; // Echo each match to a newline
}
}
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 2 years ago.
I am trying to build an application that detect if user's input(first 20 byte) exist on my database.
But I am stuck at sanitizing and making placeholder to it. Especially, this part $stmt->execute(), any advise and recommendation will be appreciated!
<?php
echo <<<_END
<form method='post' action='test.php' enctype='multipart/form-data' >
Tester: <input type='file' name='uploadfile'>
<input type='submit'>
</form>
_END;
if($_FILES){
require_once 'login.php';
if (!$conn) {
die(mysql_fatal_error());
}
$type = $_FILES['uploadfile']['type'];
if($type == "text/plain"){
$name = $_FILES['uploadfile']['name'];
$fh = fopen($name, 'r') or die("File Does not exist");
$content = file_get_contents($name, FALSE, NULL, 0, 20);
$content = sanitizeMySQL($conn, $content);
fclose($fh);
$stmt = $conn->prepare("SELECT * FROM storage WHERE mydata like ?");
$stmt->bind_param("s", $content);
$stmt->execute();
//$stmt->bind_result($content);
if (!$stmt) {
echo "Not Exist";
} else {
echo "Exist";
}
} else {
echo "txt only <br>";
}
}
This section of your code is already sanitising your input.
$stmt = $conn->prepare("SELECT * FROM storage WHERE mydata like ?");
$stmt->bind_param("s", $content);
$stmt->execute();
The first line lays out your sql query with parameters.
$stmt = $conn->prepare("SELECT * FROM storage WHERE mydata like ?");
The second line escapes any dangerous characters in the user input (i.e. in $content), and binds it to the position of the ? in your query in the line above.
$stmt->bind_param("s", $content);
The third line runs the query you created with the parameters you bound.
$stmt->execute();
An insecure method of doing this would look like this:
$stmt = $conn->prepare("SELECT * FROM storage WHERE mydata like '$content'");
If a user were to submit content which looked like this '; drop * from storage;//, then the resulting query would be:
SELECT * FROM storage WHERE mydata like ''; drop * from storage;//'
This would end up deleting all the data in your mydata table in your database.
Iam very new to PHP and I have been told that my previous code can be SQL injected so I am trying to solve it now. This is what I have come up with so far. When I submit into my form with this code below I get this error:
Notice: Undefined variable: mysqli in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 49
Fatal error: Call to a member function prepare() on null in /Applications/XAMPP/xamppfiles/htdocs/index.php on line 49".
I have commented on line 49.
<?php
$mysql_pekare= new mysqli ("localhost", "username","pass", "database");
if(!empty($_GET['namn'])) {
$unsafe_variable = "Welcome ". $_GET["namn"]. ". You are ".$_GET["age"]. " years old." ;
$stmt = $mysqli->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES('$_GET[namn]', '$_GET[age]')");` //this is line 49
$stmt->bind_param("s", $unsafe_variable);
$stmt->execute();
$stmt->close();
$mysqli->close();
}
?>
My form looks like this:
<form id="Personinfo" action="index.php" >
<input type="text" id="namn" name="namn" placeholder="namn"/>
<input type="text" id="age" name="age" placeholder="age"/>
<input type="submit"/>
</form>
You first create $mysql_pekare and then try to use $msqli. That's your issue.
Change your variables to match, and you should be good.
$mysql_pekare = new mysqli(...);
$mysql_pekare->prepare(...);
You have to use the connection as you have named it:
$mysql_pekare= new mysqli ("localhost", "username","pass", "database");
if(!empty($_GET['namn'])) {
$unsafe_variable = "Welcome ". $_GET["namn"]. " You are ".$_GET["age"]. " years old." ;
$stmt = $mysql_pekare->prepare("INSERT INTO Personinfo(`Personname`, `Personage`) VALUES(?,?))";
$stmt->bind_param("ss", $_GET['namn'], $_GET['age']);
$stmt->execute();
$mysql_pekare->close();
}
Once you do that you have to use placeholders (?) for each unsafe variable and then bind to those variables.
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
$result = mysql_query("SELECT * FROM customers
WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
if(mysql_num_rows($result) == 1)
{
while($recarr = mysql_fetch_array($result))
{
$_SESSION[customerid] = $recarr[customerid];
$_SESSION[ifsccode] = $recarr[ifsccode];
$_SESSION[customername] = $recarr[firstname]. " ". $recarr[lastname];
$_SESSION[loginid] = $recarr[loginid];
$_SESSION[accstatus] = $recarr[accstatus];
$_SESSION[accopendate] = $recarr[accopendate];
$_SESSION[lastlogin] = $recarr[lastlogin];
}
$_SESSION["loginid"] =$_POST["login"];
header("Location: accountalerts.php");
}
else
{
$logininfo = "Invalid Username or password entered";
}
Notice: Undefined index:login and
Notice: Undefined index:password
try to help me out
getting error message in second line
It seems as if u did not pass the POST params used inside your query:
> $result = mysql_query("SELECT * FROM customers
> WHERE loginid='$_POST[login]' AND accpassword='$_POST[password]'");
You have to send key value pairs explicitly to your script. One for login and one for password.
You need to wrap the index names in quotes, and your query string is hella messy.
$query = sprintf(
"SELECT * FROM customers WHERE loginid='%s' AND accpassword='%s'",
$_POST['login'],
$_POST['password']);
$result = mysql_query($query);
That whole thing should be wrapped in a block like:
if( isset($_POST['login']) && isset($_POST['password']) ) {
//code here
} else {
echo "No username/password supplied.";
}
mysql_* functions are going away, learn to use mySQLi or PDO.
Your query is as wide-open to SQL injection as anything could ever possibly be. Look into parameterized queries with mySQLi or PDO, or at least validating your data before including it in your query.
Here's a PDO example:
//create DB object
$dbh = new PDO('mysql:host=mysql.domain.com;dbname=mydb', $username, $password);
//write query
$query = "SELECT * FROM customers WHERE loginid = ? AND accpassword = ?";
//define parameters to replace ?
$params = array($_POST['login'], $_POST['password']);
//prepare the statement
$sth = $dbh->prepare($query);
//execute
if( ! $sth->execute($params) ) {
//error reporting
die('Query failed: ' var_export($dbh->errorInfo(), true));
}
//fetch all results as associative array
$results = $dbh->fetchAll(PDO::FETCH_ASSOC)l
//display
var_dump($results);
I am using PHP to try and update information I have in a mysqli table. I have decided to try and use mysqli rather than mysql. Unfortunately I cant seem to find my answer anywhere because im also trying to complete it Procedural style, as I have no knowledge of OOP and all tutorials (that i have found) are in OOP.
Below is the script I have created. I have added comments to say what I think each command is doing.
<?php
DEFINE('DB_USER', 'root');
DEFINE('DB_PASS', 'password');
DEFINE('DB_NAME', 'test');
DEFINE('DB_HOST', 'localhost');
//connect to db
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME) or die(mysqli_connect_error($dbc));
mysqli_set_charset($dbc, 'utf8');
//form not submitted
if(!isset($_POST['submit'])){
$q = "SELECT * FROM people WHERE people_id = $_GET[id]";//compares id in database with id in address bar
$r = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r, MYSQLI_ASSOC);//returns results from the databse in the form of an array
}else{//form submitted
$q = "SELECT * FROM people WHERE people_id = $_POST[id]";//compares id in database with id in form
$r2 = mysqli_query($dbc, $q);//query the database
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);//returns results from the database in an array
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$hobby = $_POST['hobby'];
$id = $_POST['id'];
//mysqli code to update the database
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
//the query that updates the database
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
//1 row changed then echo the home page link
if(mysqli_affected_rows($dbc) == 1){
echo "home page";
}
}
?>
The update form
<form action="update.php" method="post">
<p>First name<input type="text" name="fname" value="<?php echo "$person[people_fname]" ?>" /></p>
<p>Last name<input type="text" name="lname" value="<?php echo "$person[people_lname]" ?>" /></p>
<p>Your age<input type="text" name="age" value="<?php echo "$person[people_age]" ?>" /></p>
<p>Your hobby<input type="text" name="hobby" value="<?php echo "$person[people_hobby]" ?>" /></p>
<input type="hidden" name="id" value="<?php echo $_GET['id'] ?>" />
<input type="submit" name="submit" value="MODIFY" />
</form>`
When I submit the form I get the following error message
Warning: mysqli_error() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\sandbox\update.php on line 39
I realize this is telling me the issue is with
$r = #mysqli_query($dbc, $update) or die(mysqli_error($r));
So I have tried to put the sqli code in as the second parameter (i realize this is the same as putting the variable in, but it was a last resort), but it didn't seem right and still didn't work. I have also looked a php.net but couldn't work out the answer from the example they have given
Please advise, I thought this was meant to be simple?
$update = "UPDATE people
SET people_fname = $fname,
people_lname = $lname,
people_age = $age,
people_hobby = $hobby
WHERE people_id = $id";
You need to quote out the variables:
$update = "UPDATE people
SET people_fname = '$fname',
people_lname = '$lname',
people_age = '$age',
people_hobby = '$hobby'
WHERE people_id = '$id'";
HOWEVER
You should look into bound parameters - you're taking user input and writing it straight into your database, which means that a malicious user can do all sorts of mischief.
Have a look at the manual page for mysqli's bind_param - there are plenty of example code snippets.
Don't pass $r to mysqli_error. It accepts an optional mysql link, but not a query result anyway.
In your case, the query is executed. That evaluates to false, which is assigned to $r. The assignment evaluates to false, causing you to call die(mysqli_error($r)) with $r being false.
I think you meant to pass $dbc to mysqli_error.
Looks to me like the problem is with the database connection ($dbc). Because you are using
#mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME)
The '#' may be hiding the connection error somehow.
Also, please tell me you're doing data sanitisation in real life, right? If not, you have to run mysqli_real_escape_string() on all the POST and GET data.
you wrote
//returns results from the database in an array
$person = mysqli_fetch_array($r2, MYSQLI_ASSOC);
but you should write
//returns results from the database in an array
$person = mysqli_fetch_array(MYSQLI_ASSOC);