When trying to fetch data from a Mysql database using PHP, the following code gets a message:
Getting error:
undefined variable result.
<?php
require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error);
echo <<<_END
<form action="fetchdata.php" method="post"><pre>
Enter Country <input type="text" name="field">
<input type="submit" value="Display Records">
</pre></form>
_END;
if (isset($_POST['field'])) {
$field=$_post($conn,'field');
$query="SELECT * FROM customers WHERE Country = '$field'";
$result=$conn->query($query);
if (!$result) die($conn->error);
}
$rows = $result->num_rows;
Instead of
$field=$_post($conn,'field');
Maybe you mean
$field=$_POST['field'];
Additionally you use $result at the end, even when it is not defined:
$rows = $result->num_rows;
Also you never output any data and print it. You just store it in variables.
In any case: What you are doing there by writing form data directly into a query string, is dangerous. I recommend you to use PDO together with Named Parameters. Also maybe read up about SQL injections.
Here is another stackoverflow question with a nice answer, regarding SQL injections. It includes both PDO and mysqli: https://stackoverflow.com/a/60496/6637731
Without telling how request to this code is done, one guess is that isset($_POST['field']) returns false, hence variable $result is never defined but you use it anyway below in $result->num_rows.
You made a mistake in the below line. It should be
$field=$_POST['field'];
not
$field=$_post($conn,'field');
Related
We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection
I've spent today going through tons of similar questions and trying to figure out what is wrong with my code, lots of issues people had with back ticks, quotes, etc but none seem to help or change my cause. My code is no producing any errors, but when I use echo to print out my query results, it seems that the id is not getting a value.
In my delete.php:
<?
ini_set('display_errors',"1");
$username="xxx";
$password="xxx";
$database="xxx";
$conn = new mysqli(localhost, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = (int)$_GET['number'];
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id."");
$conn->close();
?>
And the delete button in my main.php (the rest of the php is correctly displaying my table with data):
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
Can someone help pick out what is causing my rows not to delete when I hit the delete button that I have created, or maybe something that more clearly can help me debug? (I don't want to use checkboxes for this).
EDIT:
I also tried this code (while defining the function as $sql and I'm getting a "Success" message:
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
EDIT 2:
I changed the structure following the advice that I should use POST, thinking I might have caught something I didn't notice before, but still not working.
echo "<td><form method='post' action='delete.php'>
<input type='hidden' name='row_id' value=".$row['id']." />
<input type='submit' name='delete_row' />
</form>";
-
if(isset($_POST['delete_row'])) {
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");
$stmt->bind_param('i', $_REQUEST['row_id']);
$stmt->execute();
}
If I do it the above way, nothing happens. Also tried this way, and get a syntax error:
if(isset($_POST['delete_row'])) {
$id = $_POST['row_id'];
$sql = "DELETE FROM tourdates WHERE id=".$id;
mysqli_query($conn,$sql);
}
A potential problem that I can see, is that you are not quoting localhost so php will look for a constant called localhost:
$conn = new mysqli('localhost', $username, $password, $database);
^ ^ here
You are also not checking for errors so that is why you don't see any. The easiest way to fix that, is to have mysqli throw exceptions. Just add this to the top of your script:
mysqli_report(MYSQLI_REPORT_STRICT);
I also don't know if you can mix procedural and object oriented mysqli like that. You should probably stick to the OOP version.
Apart from that you should not use a link (GET request) for your delete actions. What if a web-crawler or a browser extension tries to fetch the links? Instead you should use a POST request (like a form with a button).
Edit: There is another problem which causes you not to get your ID and as you cast it to int, you will always get 0:
<td><a href='delete.php?number='".$row['id']."'>Delete</a></td>
^ Oooops, closing the href attribute value here...
Your id gets placed after the value / outside of the quote of the href value. You can easily verify this if you look at the source of your page.
You need:
<td><a href='delete.php?number=".$row['id']."'>Delete</a></td>
Replace these two parts of code in your php file, first write your host in the quotations
$conn = new mysqli('localhost', $username, $password, $database);
in your where condition you wrote id=".$id."" replace it with id=".$id
write it as:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id);
Edited:
If you want to see error in your query then use the below code:
mysqli_query($conn,"DELETE FROM tourdates WHERE id=".$id) or die(mysqli_error($conn));
why not use try and catch to see your error?
anyways try this
$stmt = $conn->prepare("DELETE FROM tourdates WHERE ID = ?");<br>
$stmt->bind_param('i', $_REQUEST['number']);<br>
$stmt->execute();
could this be the problem ?
$id = (int)$_GET['number'];
May be this would be better... ?
$id = intval($_GET['number']);
Anyway if, echo($query) print an empty id, this is probably because your parameter is not an integer.
I'm currently trying to get into php and MySQL and i'm using this little project as a learning curve, but I've hit a bump that I can't get through. I have the following code that is accessing my MySQL database and I am currently trying to echo the data out using the following search function:
<?php
ob_start();
require("config.php");
ob_end_clean();
$req=$_REQUEST['workingDate'];
$req2=$_REQUEST['location'];
mysql_connect("XXXXXXXXXXX",$username,$password);
mysql_select_db($database) or die( "Unable to select database");
if ($req!="all" && $req2!="all") $query="SELECT * FROM TrackerTable WHERE workingDate='$req' AND location1='$req2'";
else if($req=="all" && $req2!="all" ) $query="SELECT * FROM TrackerTable WHERE location1='$req2'";
else if($req!="all" && $req2=="all" ) $query="SELECT * FROM TrackerTable WHERE make='$req'";
else if($req=="all" || $req2=="all" ) $query="SELECT * FROM TrackerTable";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_query($result);
mysql_close();
$i=0;
for ($i; $i < $num; $i++){
$f12=mysql_result($result,$i,"workingDate");
$f13=mysql_result($result,$i,"location1");
echo $f12." ".$f13."<br />";
}
?>
The problem I have is that whenever I try to search the database using the following html form:
<form method="post" action="searchFunction.php" name="input" id="searchform">
<label class="section">Search Options</label><br />
<input name="workingDate" type="text" id="workingDate" placeholder="Search by Date">
<input name="location1" type="text" id="location1" placeholder="Search by Location">
<input name="submit" type="submit" id="add" value="Find!">
</form>
I get this error thrown at me:
Warning: mysql_query() expects parameter 1 to be string, resource given in /XXXXXX/XXXXXX/XXXXX/XXXX/XXXXX.com/XXXXXX/searchFunction.php on line 20
I have no idea what could be causing the problem as it all seems fairly in place to me. Is there an obvious mistake i'm making or is it all just completely messed up? I've been looking at it that long that I can't tell what makes sense anymore!
Any help would be greatly appreciated. Thanks guys!
You are sure that variable $query is defined?
This because in the statement if/elseif is where you define the variable $query.
// first define default value for your $query variable
$query="SELECT * FROM TrackerTable";
// then use your if/else statement
if ($req!="all" && $req2!="all") .....................
You have an error
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_query($result); // error here
mysql_close();
$result is not a string, is resource.
mysql_query($result);
Check http://php.net/manual/en/function.mysql-query.php for details
You're trying to run your query twice:
$result=mysql_query($query);
^^^^^^--- your SQL
mysql_query($result);
^^^^^^^---- result handle (aka resource) from previous call
The second query call is utterly irrelevant/useless. You're passing in the wrong argument to the call, and you're not capturing the return value from the query anyways. Even if it was running properly, you're throwing away the query results.
You then close your DB connection, so when you try to call mysql_result() later on, there's no more DB connection to fetch your results from.
And on top of all this, you're vulnerable to sql injection attacks.
In short, this code is a total disaster.
I was checking my webpages for SQL Injection, when the main pages didn't responded to it, I created a test script:
<?
$a = $_POST["a"];
$username="...";
$password="...";
$database="...";
mysql_connect ('...',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$ress=mysql_query("SELECT username FROM userinfo WHERE id='$a'");
$row = mysql_fetch_array($ress);
print $row[0];
?>
<form name="form" action="hackMe.php" method="POST">
<input id="a" name="a" size="150">
<input name="Submit" type="submit" value="Submit">
</form>
But when I try this line:
'; UPDATE userinfo SET email = 'steve#unixwiz.net' WHERE email = 'testusr#gmail.com
I just get an error, and no change in the database.
Any ideas why?
Quote from the manual:
mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified
Highlighting by me. mysql_query() only allows a single query query per call, the second query behind the ; is ignored.
To test SQL injection you have to use a query that doesn't need a second one to do harm.
Edit:
It IS possible to allow multiple queries, but you have to explicitly state this in the mysql_connect() call.
mysql_connect($host, $username, $password, false, 65536);
// defined by MySQL:
// #define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).