This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
I found some code for a simple database search using PHP and MySQL and I was able to make it work. However, I decided it might not be such a great idea to leave my database username and password in the PHP code within the root folder. So, I found another code sample that demonstrated how to create a config.ini file outside the root, and use a dbconnect.php file to access the database credentials. I tried to implement this, but I'm not having any luck and was wondering if someone could show me what I'm missing (I only have a rudimentary grasp of coding and am trying to learn little by little). I have included the code for all of the component files (and I changed any username/passwords/servernames to generic placeholders). Below the code I have pasted the errors that are currently being shown when I submit the search form. Thanks!
index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form action="search.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
</body>
</html>
search.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php require_once('./includes/dbconnect.php'); ?>
</head>
<body>
<?php
$query = $_GET['query'];
// gets value sent over search form
$min_length = 3;
// you can set minimum length of the query if you want
if(strlen($query) >= $min_length) { // if query length is more or equal minimum length then
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT * FROM details WHERE (`title` LIKE '%".$query."%') OR (`text` LIKE '%".$query."%')") or die(mysql_error());
// * means that it selects all fields
// details is the name of our table
// '%$query%' is what we're looking for, % means anything, for example if $query is Hello
if(mysql_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)) {
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['title']."</h3>".$results['text']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
} else { // if there is no matching rows do following
echo "No results";
}
} else { // if query length is less than minimum
echo "Minimum length is ".$min_length;
}
?>
</body>
</html>
dbconnect.php:
<?php
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
// Load configuration as an array. Use the actual location of your configuration file
$config = parse_ini_file('/home/cpanelusername/private/config.ini');
$connection = mysqli_connect($config['servername'],$config['username'],
$config['password'],$config['dbname']);
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
// Connect to the database
$connection = db_connect();
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
config.ini:
[database]
servername = localhost
username = username
password = password
dbname = username_database
Warning: mysql_real_escape_string(): Access denied for user
'root'#'localhost' (using password: NO) in
/home4/cpanelusername/public_html/...../search.php on line 29
Warning: mysql_real_escape_string(): A link to the server could not be
established in /home4/cpanelusername/public_html/......./search.php on
line 29
Warning: mysql_query(): Access denied for user 'root'#'localhost'
(using password: NO) in
/home4/cpanelusername/public_html/......../search.php on line 33
Warning: mysql_query(): A link to the server could not be established
in /home4/cpanelusername/public_html/......./search.php on line 33
Access denied for user 'root'#'localhost' (using password: NO)
This is because mysql_real_escape_string takes into account the current character set of the connection. As such, it needs a connection. :-)
Please try to connect database using below code and please let me know if you have any problem.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Scrubbing the strings that come from userland isn't sufficient to prevent SQL injection attacks. The standard way is to use a prepared query. E.g.:
$stmt = mysqli_stmt_init($this);
$result = array();
$okay = mysqli_stmt_prepare($stmt, "SELECT * FROM details WHERE (title LIKE ?) OR (text LIKE ?)");
if ($okay)
$okay = mysqli_stmt_bind_param($stmt, "ss", "%$query%", "%$text%")
else
[handle error]
if ($okay)
$okay = mysqli_stmt_execute($stmt);
else
[handle error]
if ($okay)
$okay = mysqli_bind_result($stmt, $row);
else
[handle error]
if ($okay)
while (mysqli_stmt_fetch($stmt))
array_push($result, $row);
else
[handle error]
mysqli_stmt_close($stmt);
Related
I have another question about connecting to Mysql database.
I have a simple text document with Tinymce online text editor. Online I want to change the text with the editor, save it to Mysql database and then show the new text online. I have the following scripts and I get this error from the file doAddContents.php:
Warning: mysql_real_escape_string(): Access denied for user ''#'localhost' (using password: NO) in /../doAddContents.php on line 8
Warning: mysql_real_escape_string(): A link to the server could not be established in /../doAddContents.php on line 8
I have no idea what I'm doing wrong. Here are the scripts:
first the script to connect to the database:
db.php:
<?php
function doDB() {
global $mysqli;
//connect to server and select database
$mysqli = mysqli_connect("localhost", "name", "pass", "db-name");
//if the connection fails, stop script execution
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
?>
doAddContents.php file:
<?php
include("db.php");
doDB();
$h4_block = "Contents Saved!";
$elm1 = $_POST['elm1'];
$entity_elm1 = htmlentities($elm1);
$entity_elm1 = mysql_real_escape_string($entity_elm1);
$add_contents_sql = "UPDATE tinymce_contents SET `contents`=
'$entity_elm1', `modified`=now()";
$add_contents_res = mysqli_query($mysqli, $add_contents_sql)
or die(mysqli_error($mysqli));
//close connection to MySQL
mysqli_close($mysqli);
//create nice message for user
$display_block = "<p>The page has been successfully updated.</p>";
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $display_block; ?>
View Page!
</div>
</body>
</html>
View.php file:
<?php
include("db.php");
doDB();
$h4_block = "View Page!";
$get_contents_sql = "SELECT * FROM tinymce_contents";
$get_contents_res = mysqli_query($mysqli, $get_contents_sql)
or die(mysqli_error($mysqli));
if ($get_contents_res = mysqli_query($mysqli, $get_contents_sql)) {
//fetch associative array
while ($row = mysqli_fetch_assoc($get_contents_res)) {
$id = $row['id'];
$contents = $row['contents'];
$modified = $row['modified'];
//Draw the results
$view_block ="<p>ID: ".$id."</p>";
$view_block .="<b>Contents</b>:".html_entity_decode($contents);
$view_block .="<b>Modified</b>:".$modified."<br/>";
}
}
//close connection to MySQL
mysqli_close($mysqli);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<div>
<h4><?php echo $h4_block; ?></h4>
<?php echo $view_block; ?>
Back to Page Edit!
</div>
</body>
</html>
According to the documentation of mysql_real_escape_string. The function will try to create a mysql connection if there is no connection opened with mysql_connect().
http://php.net/manual/en/function.mysql-real-escape-string.php
You should not be using mysql_real_escape_string() but mysqli_real_escape_string()
http://php.net/manual/en/mysqli.real-escape-string.php
I keep getting the following error:
Fatal error: Call to a member function fetch_array() on boolean in C:\xampp\htdocs\DeletePlayerSOLN\DeletePlayerExample_SOLN\index.php on line 10
Any idea what the problem is? I searched previous threads and tried to identify the problem for the past few hours. I'm new to PHP.
I'm using Xampp + Mysql.
MySQL connection:
127.0.0.1
3306
root
Default Schema: test
I'm connected through port 443,4433 through Xampp. So I try to connect through /localhost:443/folder..filename..
Connection:
//make a database connection object
$mysqli = new mysqli($server, $user, $pass, $database);
//test if there are database connection errors
if ($mysqli->connect_error)
die("Connect Error " . $mysqli->connect_error);
?>
Index page:
<?php
require "serverCode/connect.php";
$selectPlayer = "SELECT * FROM player ORDER BY playerLastName, playerFirstName";
$results = $mysqli->query($selectPlayer);
$ddlString = "<select name='cboPlayer' size='10'>";
while($row = $results->fetch_array())
{
$ID = $row["playerID"];
$name = $row["playerLastName"] . ", " . $row["playerFirstName"];
$ddlString .= "<option value='$ID'>$name</option>";
}
$ddlString .= "</select>";
$mysqli->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DELETE Player Page</title>
</head>
<body>
<form name="frmPlayer" action="serverCode/deletePlayer.php" method="get">
Select a player:<p><?php echo $ddlString;?>
<input type="submit" name="btnSubmit"></p>
</form>
</body>
</html>
Line 10 is "while($row = $results->fetch_array())"
It is likely that $mysqli->query() is not producing a proper object due to an error. Try replacing
$results = $mysqli->query($selectPlayer);
with
$results = $mysqli->query($selectPlayer) or trigger_error($mysqli->error."[$selectPlayer]");
I have an existing SHTML page with a few INCLUDE statements for menu's. This has worked well. To this point, my .htaccess file has looked like:
Options +FollowSymLinks
And my Include statement looked like this:
<!--#include virtual="menu_primary.shtml" -->
I have a new need to add some PHP code to the main page. The PHP code queries a Mysql database to return a single row. If the row exists in the database, I want to show it on the SHTML page. If the row does not exist, do nothing. Here's the PHP code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT notice from notification where page = 'home'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "Message is: " . $row["notice"]. "<br>";
}
} else {
echo "";
}
mysqli_close($conn);
?>
</body>
</html>
When I implemented this PHP code, the page seemed to interpret everything after the Greater Than symbol as text. When I posted that problem, someone on this forum suggested altering the .htaccess file to include a PHP parser. For a while. I altered my .htaccess file to look like this:
Options +FollowSymLinks
<FilesMatch "\.(htm|html|shtm|shtml)$">
SetHandler application/x-httpd-php5
</FilesMatch>
However when I do that, the PHP code works fine and I display the data from the database on the SHTML page, but the #Include statements no longer work. How can I enable both the PHP and #Include code together in the same SHTML page? Thanks very much for looking at this.
In your PHP script you can invoke the virtual function to work with your SSI
<?php
virtual('menu_primary.shtml');
There's a very old page that talks about this in more detail
http://www.zytrax.com/tech/php/php_ssi.htm
I have a form with PHP that saves a variable to a MySQL database. That form worked on a VPS, but when trying it on another VPS it gives an error when trying to write to the database when the field contains a ' character. So the same PHP code works on 1 VPS when the field contains a ' character, but not on the other VPS.
Here it works: http://www.zoekmachineoptimalisatie.us/test.php
and here (it's the other VPS) it gives an error: http://www.onzebruidsfotograaf.nl/test.php
My form:
<?php
$hostname = "localhost"; //host name
$dbname = "xxxxxxxx"; //database name
$username = "xxxxxxxx"; //username you use to login to php my admin
$password = "xxxxxxxx"; //password you use to login
$conn = new MySQLi($hostname, $username, $password, $dbname);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Untitled Document</title>
</head>
<body>
<?php
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = "UPDATE test SET Title='$title' WHERE BookID = " . $bookid;
$conn->query($update) or die("Cannot update"); //update or error
}
?>
<?php
$bookid = 1;
$sql = "SELECT * FROM test WHERE BookID = '" . $bookid . "'";
$result = $conn->query($sql) or die(mysql_error());
$query = getenv(QUERY_STRING);
parse_str($query);
?>
<h2>Update Record <?php echo $bookid;?></h2>
<form action="" method="post">
<?php
while ($row = $result->fetch_assoc()) {
?>
<textarea name="updatetitle" cols="100" rows="30"><?php echo $row['Title']; ?></textarea>
<table border="0" cellspacing="10">
<tr>
<td><INPUT TYPE="Submit" VALUE="Update the Record" NAME="Submit"></td>
</tr>
</table>
<?php
}
?>
</form>
<?php
if ($update) { //if the update worked
echo "<b>Update successful!</b>";
}
?>
</body>
</html>
An unescaped quote in your query will produce a syntax error. Instead of building the SQL fully your own, make use of SQL variables for your PHP variables with a Prepared Statement:
if (isset($_POST['Submit'])) { //if the submit button is clicked
$title = $_POST['updatetitle'];
$bookid = 1;
$update = $conn->prepare('UPDATE test SET Title = ? WHERE BookID = ?;');
$update->bind_param('sd', $title, $bookid);
$update->execute();
}
One of your servers has Magic Quotes enabled and the other doesn't. Magic Quotes is now considered undesirable and is deprecated, it automatically escapes input. You should turn off Magic Quotes and use a parameterised query/prepared statement instead - then there is no need to escape anything and it prevents SQL Injection.
Paramterised queries are supported by the MySQLi and PDO APIs.
because the single quote breaks the query statement. In order to prevent from it or from SQL Injection you need to use PDO or MySQLI extension. For more infor, see the article below
How can I prevent SQL injection in PHP?
In my site im trying to include on the top of each page a "banner" that is itself a separate php page that queries a MySQL database to return a number that displays.
When i goto the exact URL of the banner php url (www.sitename.com/banner.php) it works perfectly.
However, when i include the banner into another page include'banner.php' it returns the following error: Database access error 2002: Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)
I have 2 ways i need to include this, my main site pages are all php. My forum is phpbb and the file i need to include is HTML so i used (Note, i did ../ back out to the banners root, its not a matter of my file not being found.
Im assuming that when including the scope is different. How would i correctly accomplish this include?
Banner.php
<?php
require("../mysql.inc.php");
check_get($tp, "tp");
$tp = intval($tp);
$link = sql_connect();
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
if (!$result) {
echo "Database error.<br>\n";
exit;
}
list($total) = mysql_fetch_row($result);
mysql_free_result($result);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="menu_css.css" media="screen"/>
</head>
<body>
<div class="menucenter">
<div class="Online"> <? echo"$total" ?> Online</div>
</body>
</html>
mysql.inc.php
<?php
$SQLhost = "****.db.****.hostedresource.com";
$SQLport = "3306";
$SQLuser = "****";
$SQLpass = "****";
$SQLdb = "****";
function sql_connect()
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
if ($SQLport != "")
$link = #mysql_connect("$SQLhost:$SQLport","$SQLuser","$SQLpass");
else
$link = #mysql_connect("$SQLhost","$SQLuser","$SQLpass");
if (!$link) {
echo "Database access error ".mysql_errno().": ".mysql_error()."\n";
die();
}
$result = mysql_select_db("$SQLdb");
if (!$result) {
echo "Error ".mysql_errno($link)." selecting database '$SQLdb': ".mysql_error($link)."\n";
die();
}
return $link;
}
function sql_query($link, $query)
{
global $SQLhost, $SQLport, $SQLdb, $SQLuser, $SQLpass;
$result = mysql_query("$query", $link);
if (!$result) {
echo "Error ".mysql_errno($link).": ".mysql_error($link)."\n";
die();
}
return $result;
}
function check_get(&$store, $val)
{
$magic = get_magic_quotes_gpc();
if (isset($_POST["$val"])) {
if ($magic)
$store = stripslashes($_POST["$val"]);
else
$store = $_POST["$val"];
}
else if (isset($_GET["$val"])) {
if ($magic)
$store = stripslashes($_GET["$val"]);
else
$store = $_GET["$val"];
}
}
?>
#Craig, there is a possibility that the include file contains other includes which are not getting the right path. Can you paste some codes of the include file for us to validate the error ?
EDIT:
You have a missing quote at the end of the query.
$result = sql_query($link, "SELECT COUNT(*) FROM online_count);
It should be
$result = sql_query($link, "SELECT COUNT(*) FROM online_count");
EDIT:
You have a problem with the quotes. See you check_get function. $val is a variable and you dont need quotes around it. Check the below code.
if (isset($_POST[$val])) {
if ($magic)
$store = stripslashes($_POST[$val]);
else
$store = $_POST[$val];
}
else if (isset($_GET[$val])) {
if ($magic)
$store = stripslashes($_GET[$val]);
else
$store = $_GET[$val];
}
EDIT:
Also remove the quotes from $query:
$result = mysql_query($query, $link);
First things first:
Remove the # from your mysql statements and see if you are getting any other errors related to variables or so. You should not suppress errors while debugging.
Try printing the host, port, user and password variables inside the sql_connect() function and see if you are getting the correct values in your function.
If you have access to your server, check if /var/lib/mysql/mysql.sock exists, and has sufficient permissions.
srwxrwxrwx 1 mysql mysql 0 Sep 21 05:50 /var/lib/mysql/mysql.sock
If all is well till this point, you might want to troubleshoot your MySQL service further. A restart would help flush the connections, if that is the issue. Check a similar thread in SO too.