My host limits my concurrent_connections to 70. I have a mock election program that will require 250 students to vote roughly at the same time. The vote process requires 3 pages each with one connection which I kill as soon as the queries are done. Can someone help me come up with a retry algorithm in my conn code please?
$ID_sql = $_POST['name'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error || $ID_sql == NULL) {
echo "<h1>The system is experiencing too much traffic at the moment, please try again in a few minutes</h1>";
echo "<a href='index.html'>Click here to go back</a><br>";
$conn->close();
die("Connection failed: Congestion" . $conn->connect_error);
//Instead of die, I would like to try 10-25 times after short sleep() before it dies
//This should randomize the connections a bit.
}
Related
So I learn PHP, and I want to try to build something like a small monetized url shortener, just for fun! So every time somebody clicks on a users link, one click should be added in the MySQL table (for the user). I tried a lot of scripts but they all don't work.
<html lang="en-US">
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_query("UPDATE users SET 'hits' = 'hits'+1 WHERE id = 1");
?>
And after then display the clicks in the users dashboard via $row['']... but it doesn't count the clicks when I onload the page... the number in the mysql database does'nt change... what am I doing wrong. Alsom do you have and more professional idea how to do that, cause I know that this isn't a good alternative... I also have something like that , but it doesnt work too...
$user_ip=$_SERVER['REMOTE_ADDR'];
$check_ip = mysqli_query("select userip from pageview where page='1' and userip='$user_ip'");
if(mysqli_num_rows($check_ip)>=1)
{
}
else
{
mysqli_query("insert into pageview values('1','1','$user_ip')");
mysqli_query("update users set 'hits' = 'hits'+1 where id=1 ");
}
If you're used to mysql_query, you need to do this differently, a connection handle is required, no longer implicit. The best way to avoid slipping up on this is to use the object-oriented calling method:
$conn->query(...);
This approach is often substantially less verbose.
Below is a simple example program to show the problem I am having. I am searching the database for new jobs executing them then going to sleep until there are new jobs. I am doing it this way because they must be run 1 at a time. However when I execute the script the server will not let any scripts run that access the database. Why is the database locked?
ignore_user_abort(true);//if caller closes the connection (if initiating with cURL from another PHP, this allows you to end the calling PHP script without ending this one)
//set_time_limit(0); //run forever
//start up
session_start();
ini_set("log_errors", 1);
ini_set("error_log", __file__.".log");
require_once("includes/loginMaster.php");
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_DATA);
if ($conn->connect_error) die("Connection failed: " . $conn->connect_error);
//setup statement for getting tasks
$query='SELECT `id`,`uid`,`kid`,`type`,`value`,`time` FROM `data_que` WHERE `executed` IS NULL ORDER BY `time` ASC, `id` ASC LIMIT 1';
$stmtNext = $conn->prepare($query);
$stmtNext->bind_result($id,$uid,$kid,$type,$value,$time);
//get packets
while(true) {
$stmtNext->execute();$stmtNext->store_result();
while ($stmtNext->fetch()) {
/*
should do somthing here but removed for simplicity
*/
//reexecute job
$stmtNext->execute();$stmtNext->store_result();
usleep(100);
}
sleep(5);
echo "slept";
}
I was wondering if anyone could shine a light on how to read from a database and pass it on to a sessions variable. I have tried with a product id and get but it did not work.
I'm looking for the basics on how to approach the issue.
I assume that you need to read from MySQL Database (for example).
First thing to do is reading PHP/MYSQL documentation.
http://www.w3schools.com/php/php_mysql_intro.asp
Second thing is to read about PHP Sessions.
http://www.w3schools.com/php/php_sessions.asp
And for example some code:
// Connect to MySQL Database and select all records from your_table
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = $conn->prepare("SELECT * FROM your_table");
$query->execute();
if($query == TRUE) {
// query success
}
To store information in $_SESSION variable you need to:
Call session_start(); before accessing this variable
$_SESSION['your_var'] = 'your_value';
So I have a PHP page that connects first to my database and does a bunch of stuff using the information from there. Now I want to connect to another database within the same PHP page and access data from there and insert the information into my original database.
The code:
<?php
session_start();
include ("account.php");
include ("connect.php");
....
do stuff here
....
include ("account2.php");
include ("connect2.php");
...
$thing = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1" ;
$thing = mysql_query($thing);
echo "$thing";
....
....
insert information into my database
(From account.php & connect.php files)
....
?>
Everything shows up except for $thing. It says, "Invalid query: Query was empty" but I know the query I used works because when I ran it in the account2 database, I got the results I wanted. Is there something wrong with my logic or is it something else?
You are not mentioning database connection link while executing the query. May be your second database connection is defined after the 1st one in connection.php file. So interpreter is considering 2nd connection while executing the query.
Define the connection link with query,
$thing = mysql_query($thing,$conn); //$conn is your mysql_connect
You can still use the mysql_connect or similar mysql_ functions (procedural way) But all these are now deprecated. You should use mysqli_ (mysql improved) functions or go with the object oriented way.
$conn1 = new mysqli(SERVER1,DB_USER1,DB_PASS1,DB1);
$conn2 = new mysqli(SERVER2,DB_USER2,DB_PASS2,DB2);
if($conn1 ->connect_errno > 0 || $conn2 ->connect_errno > 0){
die('Unable to connect to database server.');
}
Now while executing your query,
$query = "SELECT abc, efg, hij FROM table ORDER BY RAND() LIMIT 1";
$thing = $conn1 -> query($query); //if it's second connection query user $conn2
Many web applications benefit from making persistent connections to database servers. Persistent connections are not closed at the end of the script, but are cached and re-used when another script requests a connection using the same credentials. The persistent connection cache allows you to avoid the overhead of establishing a new connection every time a script needs to talk to a database, resulting in a faster web application.
For your case, i would make 2 persistent connections, store each in it's own variable and then use one whenever i need to. Check it out using the PDO class.
//Connection 1
$dbh1 = new PDO('mysql:host=localhost;dbname=test', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
.
.
.
//Connection 2
$dbh2 = new PDO('mysql:host=localhost;dbname=test2', $user, $pass, array(
PDO::ATTR_PERSISTENT => true
));
After you finish you first database operation, then you can close the connection using
mysql_close($c) //$c = connection
And again start for next database operation.
private static function _connectDB1()
{
//give hostname, dbusername, dbpassword
$con1 = mysql_connect("localhost", "root", "rootpass");
$db1 = mysql_select_db("dbone", $con1);
}
private static function _connectDB2()
{
//if you are using different db with different credentials
//you can give here like this
// mysql_connect("mynewhost", "mynewusername", "mynewpassword")
$con2 = mysql_connect("localhost", "root", "rootpass");
$db2 = mysql_select_db("dbtwo", $con2);
}
So most basic php/mysql examples show something like this (taken from W3 Schools as a laymans example):
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
mysqli_close($con);
?>
When using external connection files, what is the correct way to close the connection (if needed at all).
Eg. We separate the above into a connection.php file which contains
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
And then have a Query.php file that contains:
<?php
require('connection.php');
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}
?>
Is it necessary to close the connection. Should there be a mysqli_close($con); at the end of the query.php file, or does it go at the end of the connection.php file and theres some sort of way to link that the query.php file will run before the connection is closed?
And/or is closing the connection even needed? Does it just close automatically after the script is complete?
Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.
Still, if your PHP script takes lots of time to execute, it's a good idea to close the connection when you don't have to do any request to the database anymore -- at least, if the long calculations are done after the queries.
This is especially true if your application is deployed on a shared hosting : your user account can generally only have a few connections opened at the same time. (That number of simultaneous opened connections can be pretty small on shared hosting ; it's generally bigger on private servers).
The reason we often don't close connections ourselfves is :
we generally don't really know when we have done all our queries --
this is especially true with pages that are made of lots of small
"blocks" ; each one of those is independant from the others, and can
do queries on its own ; so, when can we close the connection ?
web pages are generally quite fast to generate, so we don't really
bother about closing the connection to DB.
I think this may help you to resolve your problem.
It's better to use a class which perhaps extends Mysqli, for ie:
<?php
// Database class
class Database extends \mysqli
{
public function __construct($host, $user, $pass, $db)
{
//create connection
}
public function __destruct()
{
//close connection
//will call this function when class closes or PHP stops
}
}
//using the database
$db = new Database('localhost', 'user', 'pass', 'db');
$db->query("SELECT ....");