Handling MySql 'Too many connections' error on shared hosting - php

I have a website that uses a MySql database for storing user info for signing in, and also my data. This site is hosted on a shared hosting server. The problem I'm running into is that I'm occasionally getting a SQL too many connections error. My max connections is set at the default 151.
I am using php for all my server side scripts, and using mysqli pdo connections.
Here is some sample code to show how I handle sql connections from my php scripts. I removed anything that wasn't relevant to the issue, such as input filtering, and character escaping.
<?php
require("common.php");
//get POST data
//My database query
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
//set params for prepared statements
$query_params = array(
':username' => $_POST['username']
);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again.";
}
$row = $stmt->fetch();
//do my password hashing, and checking, and sign in user using data in $row
}
?>
Here is my common.php where the error is thrown. I'm not sure what the correct way is to handle it, as i would like the code to try several times before failing.
<?php
$username = "username";
$password = "**************";
$host = "localhost";
$dbname = "mydbname";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "";
try {
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$miscErr = "Something failed, please try again";
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

I know this has been a while, but here is the solution that I came up with. Since there is no way for me to prevent the errors, i simply handle them with the following code in my common.php file.
$db = ""; // db object
$er = ""; // error object
/*setdb() is the function that actually gets and starts the db connection.
It returns either the db object, or false. The loop will try up to 5 times
to connect with .1 second breaks in between. if that fails then it logs an
error, and the page fails to load. This has not happened in over 5 months on
a live site.*/
for ($i = 0; $i = 5; $i++) { // short loop
if (setdb() !== false) {
$db = setdb(); // if successful breaks
break;
} else {
if ($i = 5) { // after 5 trys, logs error.
file_put_contents('sqlerror.er', $er . "\r\n", FILE_APPEND);
}
}
usleep(100000); // .1second sleep
}
function setdb(){
$username = "my-username";
$password = "***************";
$host = "localhost";
$dbname = "my_database";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$miscErr = "[1040] Too many connections";
try { // try to make connection
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex) {
$er = $ex;
$pos = strpos($ex, $miscErr);
if ($pos !== false) {
return false; //return false on error
}
file_put_contents('sqlerror.er', $ex . "\r\n", FILE_APPEND);
}
return $db; // return true
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
session_start();

Related

How to check whether mysql update query is successful or not?

function insertNewBidPrice($code, $newBidPrice)
{
global $conn;
$sql = "update auctionitem set highestbid=$newBidPrice where code=$code";
//echo $sql;
if($conn->query($sql))
{
return 1;
}
else
{
require 0;
}
}
I have this php fuction that results 0 all time although update query successfully update the table.
I use PDO.
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Create a statement object first, using prepare.
$stmt = $conn->prepare($sql);
$worked = $stmt->execute();
if ($worked == TRUE) {
//I did stuff
} else {
// nope
}
function insertNewBidPrice($code, $newBidPrice) {
global $conn;
// write your query
$sql = "UPDATE auctionitem SET highestbid='$newBidPrice' WHERE code='$code'";
// run the query
$result = $conn->query($sql);
// check the result of the query
if ($result == true) {
// it was a success
return 1;
} else {
return 0;
}
}
global $conn;
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "my_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
// it worked
}
Here you go this should do the trick. I noticed you say "require 0" in your if else statement it needs to be a return. Other then that i'm not sure on your problem but there are 2 possibilities i can think of.
Your $conn variable is invalid. Check it has the correct credentials, see the $conn->connect_error line, it is in the code i wrote but also here: http://php.net/manual/en/mysqli.connect-error.php.
Possibly the query incorrect. Personally i format everything with capitals ect. as my text editor colors it when i do that and it is easy for me to see what is what. Also there were no quotes surrounding the variables in your SQL statement, this is fine if it is an integer but if you are accidentally passing a string it will fail.
Also check that you have selected the correct table ect. in your SQL.

Updating data in DataBase with PHP

I have a simple script that should Update variable in a column where user login equals some login.
<?PHP
$login = $_POST['login'];
$column= $_POST['column'];
$number = $_POST['number'];
$link = mysqli_connect("localhost", "id3008526_root", "12345", "id3008526_test");
$ins = mysqli_query($link, "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'");
if ($ins)
die ("TRUE");
else
die ("FALSE");
?>
but it doesn't work. It gives me - FALSE. One of my columns name is w1 and if I replace '$column' in the code with w1 it works fine. Any suggestions?
Simply remove quotes: '$column' = should be $column =
Your code is open for SQL Injection, use prepared statements.
change this "UPDATE test_table SET '$column' = '$number' WHERE log = '$login'"
to this "UPDATE test_table SET '".$column."' = ".$number." WHERE log = '".$login."'"
It's possible that your error is to do with the $column being set as a string with single quotation marks? Because it returns false, it suggests that you have a MySQL error of some sort.
To find out what the error message is, on your else block, rather than dying with a "FALSE" message, try use mysqli_error($link) - this should give you your error message
If removing the quotes surrounding the $column doesn't work, you could try the PDO method. Here's the snippet:
function insertUser($column, $number, $login) {
try
{
$connect = getConnection(); //db connection
$sql = "UPDATE test_table SET $column = '$number' WHERE log = '$login'";
$connect->exec($sql);
$connect = null;
} catch (Exception $ex) {
echo "EXCEPTION : Insert failed : " . $ex->getMessage();
}
}
function getConnection() {
$servername = "localhost";
$dbname = "my_db";
$username = "root";
$password = "12345";
try {
$connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Exception $ex) {
echo "EXCEPTION: Connection failed : " . $ex->getMessage();
}
return $connection;
}
Regarding $number, I'm not sure the datatype for the $number whether quotes or not is needed so experiment with or without quotes to see which one works.
And the getConnection() function is in separate PHP file where it will be included in any PHP files that calls for database connection.

PHP bindParam not working - blindValue is not the solution

I can't figure this out. I've googled it and a lot of answers refer to blindValue as the solution but I've also tried that with no luck.
The problem is that the SELECT statement is returning zero records but it should return one record. If I hard code the values into the SQL statement it works but passing them in as parameters isn't. Can some one please help me out with this? Thanks.
<?php
function checklogin($email, $password){
try
{
// Connection
$conn;
include_once('connect.php');
// Build Query
$sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = :email AND Password = :password';
// $sql = 'SELECT pkUserID, Email, Password, fkUserGroupID FROM tbluser WHERE Email = "a" AND Password = "a"';
// Prepare the SQL statement.
$stmt = $conn->prepare($sql);
// Add the value to the SQL statement
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password', $password, PDO::PARAM_STR);
// Execute SQL
$stmt->execute();
// Get the data in the result object
$result = $stmt->fetchAll(); // $result is NULL always...
// echo $stmt->rowCount(); // rowCount is always ZERO....
// Check that we have some data
if ($result != null)
{
// Start session
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Search the results
foreach($result as $row){
// Set global environment variables with the key fields required
$_SESSION['UserID'] = $row['pkUserID'];
$_SESSION['Email'] = $row['Email'];
}
echo 'yippee';
// Return empty string
return '';
}
else {
// Failed login
return 'Login unsuccessful!';
}
$conn = null;
}
catch (PDOexception $e)
{
return 'Login failed: ' . $e->getMessage();
}
}
?>
the connect code is;
<?php
$servername = 'localhost';
$username = 'admin';
$password = 'password';
try {
// Change this line to connect to different database
// Also enable the extension in the php.ini for new database engine.
$conn = new PDO('mysql:host=localhost;dbname=database', $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();
}
?>
I'm connecting to mySQL. Thanks for the help,
Jim
It was a simple but stupid error.
I had a variable called $password also in the connect.php file which was overwriting the $password that I was passing to the checklogin.
Jim

Fetching PDO - $handler vs $stmt?

I am VERY new to PHP / PDO, so please be gentle...
I am trying to enter code into my database and then fetch it into a webpage. I am able to do the first but am having difficulty displaying it. I am wondering if it's because i'm trying to combine $stmt and $handler together?
This is my code for entering the information into the database:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO survey (storename, receipt, date_visit)
VALUES (:storename, :receipt, :date_visit)");
$stmt->bindParam(':storename', $storename);
$stmt->bindParam(':receipt', $receipt);
$stmt->bindParam(':date_visit', $date_visit);
// insert a row
$storename = $_POST['storename'];
$receipt = $_POST['receipt'];
$date_visit = $_POST['date_visit'];
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
It works perfectly.
This is my code for fetching information from my database.
<?php
try {
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');
$handler->setAttribute(PDO::ATRR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
die();
}
class SurveyEntry {
public $id, $storename, $receipt, $date_visited,
$entry;
public function __construct() {
$this->entry = "{$this->storename} posted: {$this->receipt}";
}
}
$query = $handler->query('SELECT * FROM survey');
$query->setFetchMode(PDO::FETCH_CLASS, 'SurveyEntry');
while($r = $query->fetch()) {
echo $r->entry, '<br>';
}
?>
I can confirm that it connects correctly, but I can't get it to display any information. I'm wondering if it's something to do with the difference in $stmt and $handler that i'm using? I've been following tutorials online and have quite possibly mixed 2 tutorials together to try and achieve what i'm looking for.
UPDATE:
I managed to get it to work by updating how I called from the database:
$host = "localhost";
$dbname = "test";
$user = "test";
$password = "test";
$handler = new PDO( "mysql:dbname=$dbname;host=$host" , $user , $password );
Figured it out - I had 'ATRR_ERRMODE' instead of 'ATTR_ERRMODE' (typo)
how are you?
You should try to fix it:
1- Two different connections:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$handler = new PDO('mysql:host=localhost;dbname=test', 'test', 'test');

PHP: PDO prepare() causing halt in script

I am working on a simple database helper for part of a test site. I want to be able to access a database by simply doing:
require_once 'include/database_system.php'
...
$row = DB_query("SELECT userID FROM users WHERE username = :username",
array(':username' => $ourUsername));
So I've written up a little script to do so:
<?php
session_start();
$username = "xxxx";
$password = "xxxx";
$host = "localhost";
$dbname = "xxxx";
$dboptions = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
var_dump($db);
}
catch(PDOException $ex)
{
die("MySQL: Failed to connect to API Testing Database");
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
var_dump($db);
// break magic quotes
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function break_magic_quotes(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
break_magic_quotes($value);
}
else
{
$value = stripslashes($value);
}
}
}
break_magic_quotes($_POST);
break_magic_quotes($_GET);
break_magic_quotes($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
function DB_query($query, $queryArgs)
{
global $db;
echo 'TRYING TO QUERY SERVER ';
var_dump($query);
var_dump($queryArgs);
var_dump($db);
try
{
echo 'PREPARE ';
$stmt = $db->prepare($query);
echo 'EXECUTE ';
$result = $stmt->execute($queryArgs);
}
catch(PDOException $ex)
{
echo "QUERY FAILED: $query";
die("Query failed: " . $query);
return;
}
echo 'SERVER QUERY OK';
return $stmt->fetch();
}
So naturally, I'm working on a bit of form action code for the login page, by doing:
require_once 'database.php'
....
$row = DB_query("SELECT * FROM users WHERE username = :username",
array(':username' => $_POST['u']) );
The output is not very conclusive at all. Not only does it fail to get past the $db->prepare() statement, but it doesn't even look like the PDO is valid.
object(PDO)#1 (0) { } object(PDO)#1 (0) { } TRYING TO LOGINobject(PDO)#1 (0) { } TRYING TO QUERY SERVER string(46) "SELECT * FROM users WHERE username = :username" array(1) { [":username"]=> string(4) "derp" } NULL PREPARE
I don't know why it would be doing any of this. I have checked the PHP settings and it looks like PDO is properly turned on. I have checked everything up and down and I haven't been able to get anywhere. If anyone has any insight, that would be great.

Categories