Can't connect to MySQL server with PDO [duplicate] - php

This question already has answers here:
How can I get useful error messages in PHP?
(41 answers)
Closed 7 years ago.
I'm trying to prevent SQL injection using PDO, but I can't seem to connect. This is the working version - not SQL injection safe:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
// Connect to database server
mysql_connect("localhost", "********", "********") or die(mysql_error());
// Select database
mysql_select_db("mydatabase") or die(mysql_error());
// The SQL statement is built
$strSQL = "INSERT INTO mytable(name) VALUES('" . $_POST["name"] . "')";
// The SQL statement is executed
mysql_query($strSQL) or die (mysql_error());
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
This is working just fine. I read these pages on how to use PDO to protect against SQL injection attacks:
http://www.w3schools.com/php/php_mysql_connect.asp
http://www.w3schools.com/sql/sql_injection.asp
and wrote the following code following the guideline:
<html>
<head>
<title>Insert data into database</title>
</head>
<body>
<?php
session_start();
$_SESSION['name'] = $_POST['name'];
$servername = "localhost";
$username = "********";
$password = "********";
try {
$conn = new PDO("mysql:host=$servername, dbname=mydatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
echo "You have connected to the database server with PDO"
// The SQL statement is built
$stmt = $dbh->prepare("INSERT INTO mytable (name)
VALUES (:name)");
$stmt->bindParam(':name', $_POST['name']);
$stmt->execute();
// Close the database connection
mysql_close();
echo "Your name is " . $_POST["name"] ;
?>
</body>
</html>
But this code just gives me a blank page - no error message and nothing inserted into the database.
I also tried doing the connection as described in
http://www.stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
but the result was the same - a blank page without error messages.
What am I doing wrong?

You're using the wrong variable for $stmt = $dbh->prepare
which should be $conn and not $dbh as per your connection.
Having used error reporting, would have signabled an undefined variable dbh notice/warning.
You also can't use mysql_close(); with PDO as you are mixing APIs, which you can't do.
See Example #3 Closing a connection of "Connections and Connection" in the manual http://php.net/manual/en/pdo.connections.php
Another thing session_start(); is best to be above anything. You may be outputting before header.
Edit: You forgot a semi-colon in this line:
echo "You have connected to the database server with PDO"
which should read as
echo "You have connected to the database server with PDO";
which will break your code.
Error reporting would also have caught that syntax/parse error.
http://php.net/manual/en/function.error-reporting.php
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.

Related

How do I obtain data through a MySQL Database using GET in PHP?

I've tried the solutions in this question, however mysql has been depricated for mysqli. Even with these changes it still doesn't return the information, instead returns an error, with nothing else (Nothing is heard from mysqli)
What i'm trying to do is kind of similar to the question linked, however it would look like this in the url: example.com?view-work=A01 It would search for A01 in the database, then return the Name, description, an image URL and date it was made live.
This is the code that i've been able to make using the answers from the question:
<?php
//Establishing a connection to the Artwork Database
mysqli_connect('localhost', 'dbuser', 'dbpassword');
mysqli_select_db('db');
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_real_escape_string($artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($sql);
if (!$result) {
echo "Something's gone wrong! ".mysqli_error();
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>
Seems like the cause of these errors was my own incompetence, also probably the fact I'm kind of new to PHP and MySQL in general. I learnt that I needed to reference my connection in some of the commands for them to successfuly process after adding the debug exception mentioned in the OP's comments.
As someone also pointed out, Yes this code is still vulnerable to other types of SQL injection, I'll be addressing these before the final version of the code goes live.
Fixed Code:
<?php
//Establishing a connection to the Artwork Database
$link = mysqli_connect('localhost', 'dbusr', 'dbpasswd', 'db');
//Exeptional Debugging
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
if (!$link) {
echo "Error: Unable to connect to MySQL!";
echo "Error No.".mysqli_connect_errno();
echo "Error in question: ".mysqli_connect_error();
exit;
}
$artworkidentifier = $_GET["view_work"];
//Returning the result, if there is one
$artworkidentifier = mysqli_escape_string($link, $artworkidentifier);
$sql = "SELECT * FROM ArtDB WHERE art_refcode = '$artworkidentifier'";
$result = mysqli_query($link, $sql);
if (!$result) {
echo "Something's gone wrong!"; //This line will be changed later to sound more professional
}
$data = mysqli_fetch_assoc($result);
echo $data["Artwork_Name"];
echo $data["Artwork_Description"];
echo $data["Artwork_URL"];
echo $data["DateUploaded"];
?>

User co_p already has more than 'max_user_connections' active connections

I have a PHP Code to insert some information from a large text file
in the beginning of the file i have this code:
<?php
$host = "localhost";
$username = "user";
$password = "pass";
$db = "dbname";
mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($db) or die(mysql_error());
mysql_close;
set_time_limit(0);
$fh = fopen("file.txt", "r");
while ($row = fgets($fh)) {
//// CODE ....
mysql_query("INSERT IGNORE INTO `TABLE` VALUES (NULL, '$ETC', '$ETC', '$ETC')");
}
fclose($fh);
?>
but after some iserts i got this error :
Warning: mysql_connect(): User co_p already has more than 'max_user_connections' active connections in /home/username/public_html/file.php on line 7
User co_p already has more than 'max_user_connections' active connections
any solution for this problem ?
I'm the OWNER of the SERVER !
mysql_close;
should be generating an error.
This command should be
mysql_close();
Add error reporting to the
top of your file(s) while testing right after your opening PHP tag for example
<?php error_reporting(E_ALL); ini_set('display_errors', 1); to see if it yields anything.
But I have to ask, why are you connecting to the database and then closing the connection straight after?
After more code added.
As you are actually trying to access the database, you dont want to do a mysql_close(); where you have coded it.
But I have to add:
Every time you use the mysql_
database extension in new code
this happens
it is deprecated and has been for years and is gone for ever in PHP7.
If you are just learning PHP, spend your energies learning the PDO or mysqli database extensions and prepared statements.
Start here
Try to close mysql connection:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
....
mysql_close($link);

php can not execute after selected mysql db [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
here is my code, as you can see, I just wanna to connect mysql then insert a info field, but it seems not execute the next code after selected the db code, I am a newer in php, and it did not return an error, so I do not know where am I wrong..
<html>
<body>
Welcome <?php echo "show" ?><br>
Your email address is:
<?php
$servername = "localhost";
$username = "root";
$password = "123456";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "mysql successed connected.";
mysql_select_db("flowers", $conn) or die("database flowers failed".mysql_error()) ;
echo "database successed";
$sql="INSERT INTO flowers (username, password)
VALUES
('$_POST[name]','$_POST[email]')";
if (!mysql_query($sql,$conn))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($conn);
?>
</body>
</html>
test demo info
and here is the db info:
dn info
I use ubuntu 16.04 apache2
So the main issue here is that you are using a combination of mysql_ and mysql functions. Note that mysql has been depreciated since PHP5 and has been completely removed in PHP7 so you should be using the newer mysqli or PDO. I personally use PDO, however have kept your code with mysqli.
<?php
$servername = "localhost";
$username = "root";
$password = "56lj0721";
// 创建连接
$conn = mysqli_connect($servername, $username, $password);
// 检测连接
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "mysql successed connected.";
mysqli_select_db($conn,"flowers") or die("database flowers failed".mysqli_error()) ;
echo "database successed";
$sql="INSERT INTO flowers (username, password)
VALUES
('$_POST[name]','$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysqli_close($conn);
?>
You should also really be using prepared statements to help prevent SQL Injection. You can read more here for mysqli.
It's also important to remember that you should be validating your $_POST['name'] and $_POST['email'] values as well, which I have not included.
If you want to read further about PDO, take a look here.
You have these two statements in your php code.
$conn = mysqli_connect($servername, $username, $password);
...
$conn = mysqli_connect($servername, $username, $password);
You should get rid of the second one if you must use the mysql_ interface to run your query.
You should also know, with respect, that only a fool uses the mysql_ interface in 2017. It has been deprecated for years, for reasons of cybersecurity, and is going away soon.

PHP variables not printing to HTML webpage

We have the following code in the HTML of one of our webpages. We are trying to display all of the Wifi speeds and GPS locations in our database using the MySQL call and while loop shown in the below PHP code. However, it doesn't return anything to the page. We put echo statements in various parts of the PHP (ex. before the while loop, before the database stuff) and it doesn't even print those statements to the webpage.
<body>
<h2>WiFi Speeds in the System</h2>
<p>Speeds Recorded in the System</p>
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbc = mysql_connect($hostname, $username, $password)
or die('Connection Error: ' . mysql_error());
mysql_select_db('createinsertdb', $dbc) or die('DB Selection Error' .mysql_error());
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
$results = mysql_query($data, $dbc);
while ($row = mysql_fetch_array($results)) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
?>
</body>
This line is incorrect, being the AND:
$data = "(SELECT Wifi_speed AND GPS_location FROM Instance)";
^^^
Change that to and using a comma as column selectors:
$data = "(SELECT Wifi_speed, GPS_location FROM Instance)";
However, you should remove the brackets from the query:
$data = "SELECT Wifi_speed, GPS_location FROM Instance";
Read up on SELECT: https://dev.mysql.com/doc/refman/5.0/en/select.html
Using:
$results = mysql_query($data, $dbc) or die(mysql_error());
would have signaled the syntax error. Yet you should use it during testing to see if there are in fact errors in your query.
Sidenote:
AND is used for a WHERE clause in a SELECT.
I.e.:
SELECT col FROM table WHERE col_x = 'something' AND col_y = 'something_else'
Or for UPDATE, i.e.:
UPDATE table SET col_x='$var1'
WHERE col_y='$var2'
AND col_z='$var3'
Footnotes:
Consider moving to mysqli with prepared statements, or PDO with prepared statements, as mysql_ functions are deprecated and will be removed from future PHP releases.
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.
"Thank you for the suggest but we tried that and it didn't change anything. – sichen"
You may find that you may not be able to use those functions after all. If that is the case, then you will need to switch over to either mysqli_ or PDO.
References:
MySQLi: http://php.net/manual/en/book.mysqli.php
PDO: http://php.net/manual/en/ref.pdo-mysql.php
hi mate i see some problem with your DB connection & query
here is example check this out
in SELECT is incorrect, being the AND .using a comma as column selectors:
and make condition for after set query & check data validation that is proper method
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "createinsertdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT `Wifi_speed `, `GPS_location `, FROM `Instance`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['Wifi_speed'];
echo $row['GPS_location'];
}
} else {
echo "0 results";
}
$conn->close();
?>

Warning: mysqli_query() expects parameter 1 to be mysqli boolean given [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 years ago.
After submitting something through my form I get the welcome part and then the mysql connection error because mysql is off, it goes away when I turn it on and then the boolean error. "Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in C:\xampp\htdocs\welcome.php on line 25"
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?><br>
Your password is <?php echo $_POST["password"]; ?><br>
You have purchased the <?php echo $_POST["sub_type"]; ?>
<?php
$mysqli_host = "localhost";
$mysql_username = "root";
$mysql_password = "123";
$site_db = "test";
$info_name = $_POST["name"];
$info_pass = $_POST["password"];
$info_email = $_POST["password"];
$sub_type = $_POST["sub_type"];
$con=mysqli_connect($mysqli_host,$mysql_username,$mysql_password,$site_db);
// Checks connection to twitch webpanel database and inserts registreation info
if (mysqli_connect_errno());
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO Users (Username, Password, Email, Subcription)
VALUES ('$info_name', '$info_pass', '$info_email', '$sub_type')");
?>
</body>
</html>
Most probably, you have a connection error in mysqli_connect. Wrong credentials or MySQL is down.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
//you need to exit the script, if there is an error
exit();
}
if (mysqli_connect_errno());
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit(); // **this is missing**
}
mysqli_query($con,"INSERT INTO Users (Username, Password, Email, Subcription)
VALUES ('$info_name', '$info_pass', '$info_email', '$sub_type')");
Here is your bug:
if (mysqli_connect_errno());
There should be no semicolon on the end.
Also according to the documentation you should be using this to check for connection errors:
if (mysqli_connect_error())
But as I said in a comment, I recommend using PDO instead of mysqli. And make sure you properly escape values inserted into the database and encrypt the password with pbkdf2 or scrypt.

Categories