PHP database insert issue - php

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.

Related

SQL Query of checking existing entry in database is not working

<?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

Warning: mysqli_query(): Couldn't fetch mysqli in C:\ ... on line 13

although this question has been asked (and answered) many times, I didn't find a solution to the problem.
Here is my code:
<?php
#session_start();
include("./include/config.php");
include("./include/db_connect.php");
include("functions.php");
if (!isset($_GET['artikelID'])){$_GET['artikelID'] = "";}
if (!isset($_SESSION['UserID'])){$_SESSION['UserID'] = "";}
$sql = "SELECT kundenID FROM kunden WHERE username = '".$_POST['myusername']."' AND password = '".md5($_POST['mypassword'])."' ";
$result = mysqli_query($connect, $sql) OR die("<pre>\n".$sql."</pre>\n".mysqli_connect_error()); // this is line 13
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result)==1){
doLogin($row['kundenID'], isset($_POST['Autologin']));
header("location:cart.php?action=add&artikelID=".$_GET['artikelID']."&id=". $_SESSION['UserID'] ." ");
}
else {
header("location:k_login.php?error=TRUE ");
}
include("./include/db_close.php");
?>
mysqli_connect_error() shows me the absolute correct sql-query; the sql-query is tested with a tool named mysql-front and brings exactly one (and the correct one) result, which is 'kundenID'.
I have tested many things (like $_SESSION['connect'] or $_GLOBALS['connect'] instead of $connect in db_connect.db), but with no result.
Can anyone please help me?
-- Update --
Why does nobody answer?
Is the description of the problem unclear?
The db-connection is established like this:
<?php
error_reporting(E_ALL);
$connect = mysqli_connect($dbserver,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()){
echo "Zeile ".__LINE__.": Datenbankverbindung ist fehlgeschlagen ! " . mysqli_connect_error();
exit();
}
?>
All the db-variables are known in the checklogin-script (tested). All the $_POST-variables are also known in the checklogin-script (tested). I even tried a hard-coded sql-query (with the real data of the test-record in the db).
The result is still the same: mysqli_connect_error() reports the correct query - but then nothing more happens.
I have spent more than 10 hours in the meantime. I really would appreciate, if someone could help me.
Couldn't fetch mysqli means that PHP is unable to identify the contents of your $connect variable as a valid mysqli connection. Try adding some error handling into "./include/db_connect.php" to get an idea of what happened to the mysqli connection that is preventing you from using it.

SQL syntax error

Im fairly new to both PHP and SQL but what i want is for the details entered into my form to be inserted into a database.
The code i have written works and the data is submitted into the database but there are a couple things not right.
Firstly here is the code;
<?php
include "credentials.php";
function insert_post($cnhost,$cnusername,$cnpassword,$cndatabase,$titlein,$contentin,$comment_optionin) {
$connect = mysqli_connect($cnhost,$cnusername,$cnpassword,$cndatabase);
if (mysqli_connect_errno($connect))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connection Success! <br>";
$submitpost_query = mysqli_query($connect,"INSERT INTO blog_posts (title,content,comment_option) VALUES ('".$titlein."','".$contentin."','".$comment_optionin."')");
if (!mysqli_query($connect,$submitpost_query))
{
die('Error: ' . mysqli_error($connect));
}else{
echo "Post submitted.";
}
mysqli_close($connect);
}
}
$title = $_POST["title"];
$content = $_POST["content"];
$comment_option = $_POST["comment_option"];
insert_post($host,$username,$password,$database,$title,$content,$comment_option);
?>
Although the data is submitted into the database as i want i get the following error;
"Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1"
The $comment_option variable contains the value 1 or 0, depending on which radio button is selected so this error might be referring to this variable but this SQL error is the same whether the value of $comment_option is 1 or 0.
I do see "Connection success!" before this error but do not see "Post submitted" even though the post is actually submitted. Any ideas why?
As well as helping me with this problem i would be very grateful if somebody could give me some general tips to improve what iv wrote. I am a noob so im sure there's a few things that could be improved here!
Thanks very much!
The problem is here:
if (!mysqli_query($connect,$submitpost_query))
You're passing a mysqli_query result which is $submitpost_query to another mysqli_query which is in the if statement.
The problem is with following chunk of code
if (!mysqli_query($connect,$submitpost_query))
it should be instead following
if (!$submitpost_query)
Reason : You are executing return object again through mysql_queri function that is causing warning, invalid resource, as this function only excepts valid sql query or connection object
I know your question is answered but I seriously recommend you to sanitize the POST data before concatenating it in a query.

Why is my include tag deleting everything after it?

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.

PHP echo a variable showing blank screen

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

Categories