php - MySQL Error 1040 "Too many connections" - php

I have this error, I have seen on several pages how to fix it, increasing the max connections variable, but I was wondering if there is any way to retry connecting 'n' number of times before throwing that error,
I am using mysqli to create my connection.
I would be very grateful for any help you could give me to get an idea of ​​how to do it if possible
update
con.php
<?php $con = new mysqli("localhost", "root", "", "grmv");
if($conexion->connect_errno) {
die ("Error: " . $con->connect_errno . "---" . $con->connect_error);
}
return $con;
?>
Products.php
<?php
include"con.php";
mysqli_query($con,"SET NAMES 'utf8'");
$result=mysqli_query($con,"select * from bio, carac where idprod=5");
while($data=mysqli_fetch_array($result)){
....
}
$conexion->close();
}
?>

More consistent way is to keep using OOP aproach, also good practice to use bind for any untrusted input, maybe not here specifically but still good practice.
$mysqli = new mysqli(
$connectionData['DB_HOST'],
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$stmt = $mysqli->prepare("select * from bio, carac where idprod=?");
$stmt->bind_param('5');
$stmt->execute();
while ($result = $stmt->fetch()) {
// do stuff
}
$stmt->close();

Related

Unknown database 'database_name' in MySQL with WAMPServer

I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.

I got 3 Days of PhP please Forgive me but Echo is killing me... What is Wrong?

I tried and read for hours...
I just cant get the last Echo to show a total id count.
I tried insert conditions in Select... Nope...
Please help...
As i said in the title i am new at this.
Doing just for 'fun'
If you could help a newbie out i would appreciate that.
<?php
$dt = new DateTime('');
$dt->setTimeZone(new DateTimeZone('Europe/Lisbon'));
echo $dt->format('d-m-Y | G:i:s');
// START CONECTION TO BD -->
if (isset($_POST['submitted'])) {
DEFINE ('DB_USER', 'YES_I_DID_THIS');
DEFINE ('DB_PSWD', 'THIS_TOO');
DEFINE ('DB_HOST', 'YEAP..I CAN USE THE TABLE FINE.. ITS NOT CONNECTION');
DEFINE ('DB_NAME', 'MYUSER');
$dbcon = mysql_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
$pnome = $_POST['pnome'];
$unome = $_POST['unome'];
$contacto = $_POST['contacto'];
$morada = $_POST['morada'];
$stamp = $_POST['stamp'];
$sqlinsert = "INSERT INTO Contactos (pnome, unome, contacto, morada, stamp) VALUES ('$pnome','$unome','$contacto','$morada','DATE: Auto CURDATE($stamp)')";
if (!mysql_query($dbcon, $sqlinsert)) {
die('');
}
$newrecord = "1 Record added to the Database";
// END INSERT DATA SCRIPT -->
}
// START COUNT TOTAL TABLE ID's
// As i said i am Noob... So i repeat this because i copied it... :)
DEFINE ('DB_USER', '-----------');
DEFINE ('DB_PSWD', '-----------');
DEFINE ('DB_HOST', '---------------');
DEFINE ('DB_NAME', '-----------');
$con = mysql_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
if (!$con) {
die("cant connect: " . mysql_error());
}
mysql_select_db("$con");
$sql = "SELECT id FROM Contactos";
count($t);
//help here please i can't show this '$t' to show at page. Thanks
echo $t ;
?>
You aren't instantiating the $t variable. You kind of need to to be able to get the value and use it.
You would've seen an error about that if you turn on error reporting:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Now your issue. You aren't even running the query.. You need to mysql_query() that $sql. I'd suggest you actually use sql's COUNT() function.
$sql = "SELECT COUNT(id) AS count FROM Contactos";
$query = mysql_query($sql);
if(!$query) {
die(mysql_error());
} else {
$count = mysql_fetch_assoc($query);
echo $count['count']; // should have your count in there.
}
You should stop using mysql_* functions. The library is deprecated.
I do understand that you've just started learning PHP and all, but it's best to start with the right libraries as mysql_* will be removed soon as it's an insecure library.
You should look into using PDO or MySQLi as they are more modern libraries and while you might have to overcome a hurdle to learn it, being competent in those libraries will do you the world of good!
Resources:
PDO
MySQLi

No result from query in PHP [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have made code without error for connection and data fetching but i don't know why result for query is bool(false)
<?php
$con=mysql_connect("localhost","root","","xyz");
echo "Connection made";
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
The code to query and execution is
<?php
include ("includes/connection.php");
$query="SELECT * FROM userdata ";
$result=mysql_query($query);
var_dump($result);
?>
Help needed here
You should use either mysql or mysqli. This is the main problem for the error
<?php
$con=mysqli_connect("localhost","root","","xyz") or die ("error in connection".mysqli_error($con);
?>
and use $result= mysqli_query($con, $sql) where $sql contains your query
As i stated in the comments, your echo up there to tell you you connected to the mysql server is not effective. I pulled out an old function from me to show you how to do it and make it clear where the error is.
$con = mysql_connect('localhost','root','');
$db = mysql_select_db('xyz',$con);
function OpenConnection(){
global $con;
global $db;
if (!$con){
die('cannot connect to server!');
}else{
if(!$db){
die('cannot connect to database!');
}
}
}
If you dont get anything back, you ll be good to go.
Don't use mysql_* functions they are depracted use mysqli or pdo instead.
You need to fetch results of your query with fetch functions like mysql_fetch_array() or mysql_fetch_row() to get results of your query. There are plenty of examples in PHP manual.
In your cause it would be something like this:
<?php
$con=mysql_connect("localhost","root","") or die("didn't connect to db");
mysql_select_db('name_of_your_db', $con);
$query="SELECT * FROM `userdata` ";
$result=mysql_query($query); //this returns resource ID that needs to be fetched
while($row = mysql_fetch_row($result))
print_r($row);
If $result is false it means that query failed it can be caused by several issues for example there is no DB selected, there is no connection etc.
I'd also give you better solution with PDO
<?php
$dsn = 'mysql:dbname=nameofyourdb;host=127.0.0.1';
$user = 'root';
$password = 'yourpass';
try
{
$db = new PDO($dsn, $user, $password);
foreach ($db->query("SELECT * FROM `userdata`") as $row)
print_r($row);
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
?>

Learning SELECT FROM WHERE prepared statements

Can someone re-write the below code as a prepared statement?
result = mysqli_query($con,"SELECT * FROM note_system WHERE note = '$cnote'")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{
$nid = $row['id'];
}
I am trying to learn prepared statements and am having trouble understanding how it works from the many examples I have found while searching. I am hoping that if I see some code I am familiar with re-written as a prepared statement that it might click for me. Please no PDO, that is too confusing for me at my current level of knowledge. Thanks.
Hello ButterDog let me walk you through PDO step by step.
Step 1)
create a file called connect.php (or what ever you want). This file will be required in each php file that requires database interactions.
Lets start also please note my comments :
?php
//We set up our database configuration
$username="xxxxx"; // Mysql username
$password="xxxxx"; // Mysql password
// Connect to server via PHP Data Object
$dbh = new PDO("mysql:host=xxxxx;dbname=xxxxx", $username, $password); // Construct the PDO variable using $dbh
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set attributes for error reporting very IMPORTANT!
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE); // Set this to false so you can allow the actual PDO driver to do all the work, further adding abstraction to your data interactions.
?>
Step 2) Require the connect.php please take a look :
require ('....../........./...../connect.php'); // Require the connect script that made your PDO variable $dbh
Step 3)
to start database interactions just do the following also please read the code comments. For the moment we will not worry about arrays! Get the full gyst of PDO then worry about making it easier to work with! With repetition the "long way" comes more understanding of the code. Do not cut corners to begin with, cut them once you understand what you are doing!
$query = $dbh->prepare("SELECT * FROM note_system WHERE note = :cnote"); // This will call the variable $dbh in the required file setting up your database connection and also preparing the query!
$query->bindParam(':cnote', $cnote); // This is the bread and butter of PDO named binding, this is one of the biggest selling points of PDO! Please remember that now this step will take what ever variable ($cnote) and relate that to (:cnote)
$query->execute(); // This will then take what ever $query is execute aka run a query against the database
$row = $query->fetch(PDO::FETCH_ASSOC); // Use a simple fetch and store the variables in a array
echo $row['yourvalue']; // This will take the variable above (which is a array) and call on 'yourvalue' and then echo it.
Thats all there is to PDO. Hope that helped!
Also take a look at this. That helped me so so much!
I also use this as a reference (sometimes) - The web site looks like crap but there is quality information on PDO on there. I also use this and I swear this is the last link! So after this any questions just ask, but hopefully this can turn into a little reference guide on PDO. (hopefully lol)
Use pdo:
http://php.net/manual/en/book.pdo.php
from various docs:
/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour';
$sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
This is one way to do it with PDO:
$sel = $db->prepare("SELECT * FROM note_system WHERE note=:note");
$sel->execute(array(':note' => $_POST['note']));
$notes = $sel->fetchAll(PDO::FETCH_ASSOC);
See the placeholder :note in the query in line 1, which is bound to $_POST['note'] (or any other variable for that matter) in line 2.
If I want to run that query again, with a different value as :note, I'll just call lines 2 and 3.
Displaying the results:
foreach ($notes as $note) {
echo $note['id'] . ": " . $note['text'] . "<br />";
}
This should help you on the right path...
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT id FROM note_system WHERE note = ?";
$stmt = mysqli_stmt_init($link);
if(!mysqli_stmt_prepare($stmt, $query)) {
print "Failed to prepare statement\n";
}
else {
$note = "mynote";
mysqli_stmt_bind_param($stmt, "s", $note);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result))
{
$nid = $row['id'];
}
}
mysqli_stmt_close($stmt);
mysqli_close($link);

mysql vs mysqli config file and queries

I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.

Categories