So I have the following PHP code
<?php
error_reporting(E_ALL & ~E_NOTICE);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
$poscote = $_POST['postcode'];
mysql_real_escape_string($poscote);
//! Checks for direct access to page
if (empty($_POST)) {
header('location:index.php?nothingentered');
die();
}
require_once('../Connections/PropSuite.php');
mysql_select_db($database_Takeaway, $Takeaway);
$query_PC = "SELECT * FROM Postcodes WHERE pc = '$postcode'";
$PC = mysql_query($query_PC, $Takeaway) or die(mysql_error());
$row_PC = mysql_fetch_assoc($PC);
if( mysql_errno() != 0){
// mysql error
// note: message like this should never appear to user, should be only stored in log
echo "Mysql error: " . htmlspecialchars( mysql_error());
die();
}
else {
echo $row_PC['oc'];
}
?>
This is to process a form with the following code
<form action="search_postcode.php" method="post">
<input type="text" name="postcode" />
<button>Go</button>
</form>
Strangely its just showing a blank screen, no errors, nothing I have checked through and cannot seem to find a solution.
Many thanks in advance for your help.
As your $postcode variable is undefined, you are looking in your database for a row where pc is an error message.
That query could very well finish without errors, but it probably produces 0 rows, so you don't have an error, nor do you have a result. In that case you output nothing, so you will see a blank screen.
You probably want:
$postcode = mysql_real_escape_string($poscote);
instead of:
mysql_real_escape_string($poscote);
and put it below the database connection section.
Also, you should switch to PDO (or mysqli) and prepared statements to avoid sql injection problems and because the mysql_* functions are deprecated. Note that your mysql_real_escape_string does not do anything (except removing the contents of your variable...) when you don't have a database connection open.
In addition to the other answers, and without mentioning that you should be using PDO or mysqli, you could be having a character encoding issue. Try doing something like this:
define('DB_CHARSET', 'ISO-8859-1');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);
...
echo "Mysql error: " . htmlentities(mysql_error(), REPLACE_FLAGS, DB_CHARSET);
Replace the value of DB_CHARSET with whatever encoding your database is using. If you try to use htmlentities() with an invalid character it will produce an empty string.
As of php.net, to enable php errors using the ini_set, you have to do it like this
ini_set('display_errors', '1')
This is taken from this link
Related
<?php
error_reporting(0);
$link = mysqli_connect("localhost", "root", "", "checksql");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$myemailaddress=$_POST['useremail'];
$mypassword=$_POST['userpassword'];
$sql = mysqli_query("SELECT * FROM register WHERE Email = '$myemailaddress' ");
$count = mysqli_num_rows($sql);
echo $count;
if($count > 0){
echo "success";
} else{
echo "failed";
}
?>
I am trying to check whether an email exists in the database or not. I searched different thread on stackoverflow and tried to correct it but failed. Even the echo of $count isn't showing it's value. Is there any other way to check it?
You didn't pass db connection to your query
$sql = mysqli_query($link, "SELECT ...
^^^^^^
Btw, your code is open to SQL injection.
Use a prepared statement
https://en.wikipedia.org/wiki/Prepared_statement
More on SQL injection:
https://en.wikipedia.org/wiki/SQL_injection
http://php.net/manual/en/security.database.sql-injection.php
How can I prevent SQL injection in PHP?
Also make sure your POST arrays are not failing you.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
error_reporting(0); doesn't help you, it turns it off.
Add or die(mysqli_error($link)) to mysqli_query() to check for errors.
http://php.net/manual/en/mysqli.error.php
Your form should be using a POST method with name attributes for both your POSTs. That is unclear and wasn't posted in your question; call it an insight.
If you are using both your form and PHP/MySQL inside the same file, then that will trigger undefined index notices on initial page load.
Use !empty() for them.
Reference(s):
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/tutorial.forms.php
http://php.net/manual/en/function.empty.php
I'm trying to create a searchable database using PHP and MySQL. I have a file called mission.html with the following code:
<html>
<body>
<form name="form1" method="post" action="mission1results.php" id="search">
<input name="search" type="text"/>
<input type="submit" name="submit" vaule="Search"/>
</form>
mission1results.php
<html>
<body>
<?php
include 'login.php';
$connection = mysqli_connect(
$db_hostname, $db_username,
$db_password, $db_database);
if(mysqli_connect_error()){
die("Database Connection Failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$q_cond = mysqli_real_escape_string($_GET['search']);
$query="SELECT * From Merchant Where MerchantName='".$q_cond."'";
$result=mysqli_query($connection,$query);
if ($result===false)
{
die("Database Query Failed!")
};
while ($row=mysqli_fetch_assoc($result)){
echo "MerchantName: ".$row["MerchantName"].",";
echo "<hr/>";
}
mysqli_free_result($result);
?>
<?php
mysqli_close($connection);
?>
</body>
</html>
When I hit submit and type in anything in the searchbar nothing appears. I don't get an error, I don't get results, its all blank. Can anyone tell me why this is?
You have a syntax error in mission1results.php
if ($result===false)
{
die("Database Query Failed!")
};
must be changed for:
if ($result===false)
{
die("Database Query Failed!");
}
Instead $_GET['search'] use $_POST['search'] because your submit forms method is post.
One of mysqli_real_escape_string parameters should be DB connection.
syntax errors in HTML, for example, vaule="Search"
syntax errors in PHP, for example, there shoudn't be ; after } in if
If you are getting a blank screen with the errors pointed out in previous answers you might want to take a look at the PHP error_reporting level on your system http://php.net/manual/en/function.error-reporting.php. You should be seeing PHP errors, on a development server I like to report PHP errors, warnings and notices.
Also, are you expecting users to enter an exact search term? You might want to consider something like:
$query="SELECT * From `Merchant` Where `MerchantName` like '%".$q_cond."%'";
First and foremost: mysqli_real_escape_string() requires a DB connection be passed, then there is your form where you are using a POST method in the form and GET for your query.
Consult the manual: http://php.net/manual/en/mysqli.real-escape-string.php
$q_cond = mysqli_real_escape_string($connection,$_POST['search']);
Plus, change
if ($result===false)
{
die("Database Query Failed!")
};
to
if ($result===false)
{
die("Database Query Failed!");
}
You also have a syntax error vaule="Search" change it to value
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Error reporting should only be done in staging, and never production.
Also or die(mysqli_error($connection)) to mysqli_query() to find any possible errors.
I'm trying to make a very basic form that inserts into my database. I've worked through countless hours working on this. I feel I understand each line of code. I can't imagine what the problem is. I'm not receiving any errors, although I haven't set up error checks in my code yet. Hopefully my problem is simple and obvious.
Here is my connect.php file. $con is my connection to a new mysqli. talk is my database.
<?php
$con= new mysqli("localhost","root","","talk");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
Here is the relevant form part of my html. title and content and the two pieces of information I'm trying to insert into my database. I include the connect.php. The textarea should be linked to the form through the form="talkform". This form uses action="process.php", which I'll cover next.
<?php
include 'connect.php';
?>
<center>
<h1>/talk/</h1>
<form method="post" action="process.php" id="talkform">
<input type="text" name="title"/><br><br>
<textarea form="talkform" rows="10" cols="80" name="content"></textarea><br>
<input type="submit" value="talk" />
</form>
And here is my process.php. I included connect.php in this file as well. Not sure if that's redundant and causing problems, but I don't think so. I also used this $_SERVER['REQUEST_METHOD'] bit you see, which I picked up from a tutorial. Not sure if there's a better way of accomplishing that. I put everything into variables. When I was working through errors, it was all on the mysqli_query line. I have the strongest suspicion that's the culprit.
<?php
include 'connect.php';
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
$title = $_POST['title'];
$content = $_POST['content'];
$operation = "INSERT INTO
main(title, content)
VALUES($title, $content);";
$result = mysqli_query($con, $operation);
}
?>
I hope that I didn't leave anything out. I've been struggling with getting a database working for over a week. It's been a painful process, and although I'm learning a lot, I'm not getting anything to work. Please help, and thank you.
use == operator to compare
if($_SERVER['REQUEST_METHOD'] == 'POST')
and quote your query variable
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
so code looks like with escape string
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$title = mysqli_real_escape_string($_POST['title']);
$content = mysqli_real_escape_string($_POST['content']);
$operation = "INSERT INTO main(title, content) VALUES('$title', '$content');";
$result = mysqli_query($con, $operation);
}
Also better to use check for post values exist or not with empty() or isset()
Line 4: if($_SERVER['REQUEST_METHOD'] == 'POST')
Better is check out directly if form was sent using if (isset($_POST['title'])).
When you call mysqli_error() you´ll find our you try to insert strings without quotes (and you don´t escape inputs - look for SQl injection).
$operation = "INSERT INTO main(title, content) VALUES('" . mysqli_real_escape_string($con, $title) . "', '" . mysqli_real_escape_string($con, $content) . "')";
You're not checking for errors after your mysqli_query call, of course you won't see any.
You're vulnerable to SQL injection. Use mysqli's prepared query syntax to avoid that. See How can I prevent SQL injection in PHP?.
Your immediate problem is that your query reads ... VALUES(foobar, baz), which is invalid. You're missing quotes around the values. However, if you properly use prepared statements, that will become a non-issue, so ignore that.
This is my code
<?php
$host="localhost";
$user="root";
$pass="admin";
$dbname="news";
$connection=mysqli_connect($host,$user,$pass,$dbname);
if(mysqli_connect_errno())
{
die("Database Connection Failed >> Error Name : " . mysqli_error() . " Error number : " . mysqli_connect_errno());
}
$html = file_get_contents('http://www.thenews.com.pk/NewsSubIndex.aspx?ID=5'); //get the html returned from the following url
$pokemon_doc = new DOMDocument();
libxml_use_internal_errors(TRUE);
$pokemon_doc->loadHTML($html);
libxml_clear_errors();
$pokemon_xpath = new DOMXPath($pokemon_doc);
$pokemon_row = $pokemon_xpath->query('//table[#id="ctl00_ContentPlaceHolder1_DataListSubIndex"]/tr');
foreach($pokemon_row as $row){
$headline= $row->nodeValue;
echo $headline;
$mysqli_query="INSERT INTO `thenews_entertainment` (`news`) VALUES ('".$headline."')";
echo $mysqli_query;
$result=mysqli_query($connection,$mysqli_query);
echo $result;
mysqli_close($connection);
break;
}
?>
I am not able to insert the record in database.But i have echo the query and the copied that query from browser and executed on mysql console and it inserts the record successfully.Why it is not inserting from my Code.
There are two essential flaws can be seen in your code.
Lack of prepared statements use
Lack of error reporting.
These two things you have to have unconditionally, despite of what you think of the matter.
However, mysqli too troublesome with first issue. So, I'd suggest to use PDO instead. In the PDO tag wiki you will find tutorials for both.
Rewrite your code to follow both these obligatory rules and you will have either data inserted or an error message which will tell you what's going wrong.
Maybe escaping your variable $headline wouldn't be a bad idea:
use this: http://fr2.php.net/mysqli_real_escape_string
I hope it will help you.
I have a PHP file included but everything after the <?php include 'RandomFile.php' ?> gets thrown away, I have no clue why! I need help with this.
RandomFile.php has the contents of:
require 'cons.php';
mysql_connect($URL, $USER, $PASS, $DBN);
$strSQL = "SELECT * FROM song";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
if($rs === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['url'] . "<br />";
}
// Close the database connection
mysql_close();
So Basically after the <?php include 'randomfile.php' ?> is included all my html after that isn't showing up visually in my browser but if I go back and edit the file it is there???
I'm guessing that cons.php is the connection file for your database. You need to specify the full path to cons.php. From the PHP Manual for require:
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it will
halt the script whereas include only emits a warning (E_WARNING) which
allows the script to continue.
So this example shows the file at the root.
require ($_SERVER['DOCUMENT_ROOT'].'/cons.php');
If it's below the DocumentRoot then you would do this:
require ($_SERVER['DOCUMENT_ROOT'].'/../cons.php');
On another note, replace all of the mysql_ functions with mysqli_. New versions of PHP will not include it as mysql_ has been deprecated.
Since you are trying a SQL query without selecting a database first, mysql fails with the error "No database selected"
The error is displayed with the code die(mysql_error());. die aborts further execution of the script. If you'd like it to continue you should just print it instead like this
if($rs === FALSE) {
print(mysql_error() . "\n"); // TODO: better error handling
}
else {
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['url'] . "<br />";
}
// Close the database connection
mysql_close();
}
The key is this line:
die(mysql_error()); // TODO: better error handling
If there is an error connecting to the database (as you described in your comment: "no database selected"), the execution will "die" and no more of the page will be sent to the browser.
As the code comment says, you need better error handling, but you might conceivably temporarily change the die to an echo and then the execution will continue.
Are you missing the semicolon (;) in the include?
Btw, you could set
<?php error_reporting(E_ALL);
ini_set('display_errors', '1'); ?>
this will show you the errors in your script.