I've been told that authCode(); isn't being re-called in the most efficient way, as it will "stack a lot of DB connections, opening and closing them quickly which is expensive in respect to resources".
Here's my code:
function authCode() {
$num1 = mt_rand(1, 2147483647);
$num2 = mt_rand(1, 2147483647);
$authcode = dechex($num1).dechex($num2);;
include("../db/71cfde725dc86.php");
$conn = mysql_connect($db_host, $db_uname, $db_pword) or die("Couldn't connect because ".mysql_error()); mysql_select_db($db_name);
$query = "SELECT COUNT(*) FROM records WHERE valcode='$authcode'";
$result = mysql_query($query) or die("SELECT query failed due to ".mysql_error());
$count = mysql_fetch_assoc($result);
$row = $count['COUNT(*)'];
if($row > 0)
{
$authcode = authCode();
}
else
{
$query2 = "INSERT INTO records (valcode) VALUES ('$authcode')";
$result2 = mysql_query($query2) or die("INSERT query failed due to ".mysql_error());
}
mysql_close($conn);
return $authcode;
}
authCode();
I'm focusing on $authcode = authCode(); and the fact that the database connection isn't closed until the end, which means if it does re-call the connection is still open (so I have heard)?
Should I close the connection after $row is assigned, and then re-open and close within the else statement?
What you should be doing is opening the connection before the first call to authCode(), and passing it in as a parameter. That way you use a single connection for all calls.
There's absolutely no need to run this function recursively. It can be done far easier with less overhead using a simple while loop. In pseudo code:
function authCode() {
... connect to database ...
while (true) {
... generate random code ...
if (code is in database) {
continue;
} else {
insert code into data base
break;
}
}
return $code
}
No recursion, one single database handle.
And beyond this, why such a lousy code generator? You'll get a variable-length code, with high chance of collisions. Why not simply use sha1 with a properly salted source string, which is far far less likely to be collide than your version. Your code has a theoretical keyspace of 32 bits, while md5 is 128bit and sha2 is 160bit.
You could pass your database connection in the function :
function authCode($conn) {
if ($db_link == null) {
$has_instantiated_connection = true;
// set the connection
}
else
$has_instantiated_connection = false;
// stuff
// recall
authCode($conn)
if ($has_instantiated_connection)
// close the connection
}
Related
I'm currently working on a project. It's almost done, there's only one big problem. I tested my code all the time with a xamp server on my computer, which worked perfectly fine. the goal is to run it (apache server, mysql database) on my raspberry pi. Now my project is finished, I came figured out the problem why my code doesn't work on my raspberry (at least not as I expected).
I turned on error reporting in PHP and came to this error message:
Notice: Trying to get property of non-object in /var/www/html/test.php on line 41
I use this function for all my SQL queries. Can someone provide a solution so I don't have to rewrite the whole code? Thanks in advance!
PS: this is just a piece of the code (the function where I pull the data out of the database + example of one of my queries)
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****"; // I just dont want to give my sql database password its nothing wrong ;)
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
print_r("ok connection");
function sqlquery ($sql, $conn, $naamtabel) {
global $myArray;
global $stateLoop;
$stateLoop = "0";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //line 41 in my code ==> do a while loop to fetch all data to an array
// output data of each row
while($row = $result->fetch_assoc()) {
$myArray[] = $row["$naamtabel"]; //alle data van kolom "tijd" in een array
}
$stateLoop = "1";
}
else { // if there are no results
}
}
$sql1 = "SELECT stopTijd FROM gespeeldeTijd WHERE naam = 'thomas' ORDER BY ID DESC LIMIT 1"; // get data with SQL query
sqlquery($sql1,$conn,"stopTijd");
if ( $stateLoop == "1") {
print_r("ok loop");
$date1 = $myArray["0"];
print_r($date1);
$myArray = [];
$stateLoop == "0";
}
}
?>
It pretty much looks like you have some sql error in your query; check if your field names in your database match those on the raspberry.
Seeing through your code it seems like you are pretty new to programming (which is no bad thing, I was once, too). So I made a few more modifications to your code showing you the prettiness of PHP
use "return" in function sqlquery instead of globals
check for errors after executing the code
use only one variable to check if data was loaded
I commented everything I changed
<?php
// Enable debugging
error_reporting(E_ALL);
ini_set('display_errors', true);
$servername = "localhost";
$username = "root";
$password = "*****";
$dbname = "test";
// Your function with some modifications
function sqlquery($sql, $conn, $naamtabel) {
$result = $conn->query($sql);
// Check for errors after execution
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
// If we have no data, we simply return an empty array
if($result->num_rows == 0)
return array();
// This is a variable we store the data we processed in
// We will return it at the end of our function
$myArray = null;
// Read all field data and store it $myArray
while($row = $result->fetch_assoc())
$myArray[] = $row[$naamtabel]; // if you use "$naamtabel" here, PHP first needs to interpret the string (= slower)
return $myArray;
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Because we use "die" above we don't need an "else"-clause
print_r("ok connection");
$sql = "SELECT `stopTijd` FROM `gespeeldeTijd` WHERE `naam` = 'thomas' ORDER BY `ID` DESC LIMIT 1";
$data = sqlquery($sql, $conn, "stopTijd");
// $data will contain $myArray (see "return $myArray" in function sqlquery)
// Instead checking for $stateLoop being "1" we check if $data contains any values
// If so, we fetched some data
if(sizeof($data) >= 1) {
print_r("ok loop");
$date1 = $data[0]; // No "0", because we are trying to get index 0
print_r($date1);
$data = array(); // Are you sure this is nessecary?
} else {
echo 'No data returned from query!';
}
?>
Note: code tipped on my smartphone -> untested!
If you don't want to adapt the code I wrote, the important part for this question is:
if(!$result)
die('mysqli error: '. htmlentities(mysqli_error($con)));
Your error Notice: Trying to get property of non-object means "you are trying to get num_rows from $result, but $result is not an object, so it can't contain this property".
So to figure out why $result is not an object, you need to get the error from $conn->query - my code above probably won't fix your error, but it will display you one you can work with (+ it's too long for a comment)
If you have a more detailed error message and you can't solve it on your own, feel free to comment; I will update my answer!
I have an application where each user gets their own database where each database has the same schema.
I have a script that performs migrations in this fashion:
SHOW databases
Iterate through databases
Execute sql statements
This can take a long time when there are complicated queries that take a lot of time (3 or more seconds)
Is there a way where I can run the sql statements for each database at the same time from one script? Is this dangerous/too resource intensive to do this?
The reason I want to do this, is to prevent downtime as much as possible.
Here is my script now:
<?php
ini_set('display_errors', 1);
set_time_limit(0);
$sql = file_get_contents('../update.sql');
$sql_queries = explode(";", $sql);
$exclude_dbs = array('horde','phppoint_forums','phppoint_site','roundcube', 'pos', 'bntennis_site', 'mysql', 'information_schema', 'performance_schema');
$conn = mysqli_connect("localhost", "root", "PASSWORD");
$show_db_query = mysqli_query($conn, 'SHOW databases');
$databases = array();
while ($row = mysqli_fetch_assoc($show_db_query))
{
if (!in_array($row['Database'], $exclude_dbs))
{
$databases[] = $row['Database'];
}
}
foreach($databases as $database)
{
mysqli_select_db($conn, $database);
echo "Running queries on $database\n***********************************\n";
foreach($sql_queries as $query)
{
if (!empty($query))
{
echo "$query;";
if (!mysqli_query($conn, $query))
{
echo "\n\nERROR: ".mysqli_error($conn)."\n\n";
}
}
}
echo "\n\n";
}
?>
I don't know if the database will hold for that load but basically I would fork the process or spawn it into the background, depending on language.
For php you can fork the process for each database basically running the migrations in parallel.
Essentially, I am trying to print out information in JSON so that I can communicate with my app, but I cannot connect to the MySQL database from a php script for some odd reason. What could it be that causes the error:
Warning: mysql_connect() [function.mysql-connect]: Lost connection to MySQL server during query in /srv/disk11/1158855/www/(myphpwebsite)/lib.php on line 13
Could not connect: Lost connection to MySQL server during query.
Also, line 13 is indicating the line in lib.php:
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
It should also be noted that this is a followup to a previous question in case anyone wanted to track down the source: MySQL issue connecting to site with php.
Lastly, I get the same error from both a localhost and a remote server using mysql
lib.php
<?
//Database Information
$dbhost = "31.170.160.76";
$dbname = "testdatabase";
$dbuser = "(personalinformation)";
$dbpass = "tested123";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass) or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//executes a given sql query with the params and returns an array as result
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
//loads up the source image, resizes it and saves with -thumb in the file name
function thumb($srcFile, $sideInPx) {
$image = imagecreatefromjpeg($srcFile);
$width = imagesx($image);
$height = imagesy($image);
$thumb = imagecreatetruecolor($sideInPx, $sideInPx);
imagecopyresized($thumb,$image,0,0,0,0,$sideInPx,$sideInPx,$width,$height);
imagejpeg($thumb, str_replace(".jpg","-thumb.jpg",$srcFile), 85);
imagedestroy($thumb);
imagedestroy($image);
}
?>
Index.php
<?
session_start();
require("lib.php");
require("api.php");
header("Content-Type: application/json");
switch ($_POST['command']) {
case "login":
login($_POST['username'], $_POST['password']); break;
case "register":
register($_POST['username'], $_POST['password']); break;
}
exit();
?>
api.php
<?php
function errorJson($msg){
print json_encode(array('error'=>$msg));
exit();
}
function register($user, $pass) {
//check if username exists
$login = query("SELECT username FROM login WHERE username='%s' limit 1", $user);
if (count($login['result'])>0) {
errorJson('Username already exists');
//try to register the user
$result = query("INSERT INTO login(username, pass) VALUES('%s','%s')", $user, $pass);
if (!$result['error']) {
//success
login($user, $pass);
} else {
//error
errorJson('Registration failed');
}
}
}
function login($user, $pass) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s' AND pass='%s' limit 1", $user, $pass);
if (count($result['result'])>0) {
//authorized
$_SESSION['IdUser'] = $result['result'][0]['IdUser'];
print json_encode($result);
} else {
//not authorized
errorJson('Authorization failed');
}
}
?>
As this is on the "connect" line, the server has been found (otherwise you get a different message) but you've not negotiated your log in.
Straight from the manual:
More rarely, it can happen when the client is attempting the initial connection to the server. In this case, if your connect_timeout value is set to only a few seconds, you may be able to resolve the problem by increasing it to ten seconds, perhaps more if you have a very long distance or slow connection.
If that isn't it, it's either a network problem or your connection has been terminated mid-authentication. Check that your mysql host doesn't have some weird validation that you're coming from a particualr IP (I say weird, as there are more standard ways of managing it than killing the authentication mid-flow), or try your PHP script from a a server that is closer to the MySQL server (closer in terms of network speed).
I figured out what was the matter. It turns out that my php code further down was conflicting with the login. That's why it wouldn't authenticate on multiple remote MySQL's and my own Localhost
I use this code to connect to a database:
#mysql_connect("localhost","root","") or die(mysql_error());
#mysql_select_db("ECOLE") or die (mysql_error());
#mysql_set_charset('utf8');
if(isset($_POST['profname_in'])){
$querycheck = "SELECT prof_som FROM prof_table
WHERE prof_som=$_POST[profsom_in];";
$_querycheck=mysql_fetch_array(mysql_query($querycheck));
if(isset($_querycheck['prof_som'])){
echo "0";
}else{
$query="INSERT INTO prof_table
VALUES('$_POST[profname_in]',
'$_POST[profcin_in]',
'$_POST[profsom_in]',
'$_POST[profville_in]',
'$_POST[profecole_in]',
'$_POST[profmat_in]',
'$_POST[profpass_in]');";
if(mysql_query($query)){
echo "1";
}
}
}
the echos is recupered by a javascript function (ajax):
function adding_prof_Reply() {
if(http.readyState == 4){
var response = http.responseText;
if(response==0){
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}else if (response==1){
document.location.href="dir_paneau.php";
}else{
document.getElementById('prof_validation').innerHTML = '<font color="red">'+response+'</font>';
}
}
}
everything works good, the problem is when I use require('anyfile') in the php code then the test if(response==0) is always false even when respose==0 ; if I remove the line of require everything works as it should.
I need the require to not repeat the connection information, any ideas?
"i need the require to not repeat the connection information"
To only connect once, put the 'connection information' in a separate file, maybe dbConnect.php and use the function require_once('dbConnect.php') in the files which need a database connection.
This ensures you only connect to your database once, which may solve your problem.
I am using this code to insert some values in MySql table:
<?php
mysql_connect("localhost","root","root");
mysql_select_db("bib");
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query);
// Display an appropriate message
if ($result)
echo "<p>Product successfully inserted!</p>";
else
echo "<p>There was a problem inserting the Book!</p>";
mysql_close();
?>
After running it into browser, the following error occurs:
"Apache HTTP Server has encountered a problem and needs to close. We are sorry for the inconvenience."
It seems that mysql_select_db("bib") statement causes it. Database is create , also table...
I am running php 5.3 and mysql 5.1 on windows xp sp 2.
Please any ideas are welcomed...
Thanks...
Any of the mysql_* functions can fail for various reasons. You have to check the return values and if a function indicates an error (usually by returning FALSE) your script has to react appropriately.
mysql_error($link) and mysql_errno($link) can give you more detailed information about the cause. But you don't want to show all the details to just any arbitrary user, see CWE-209: Information Exposure Through an Error Message.
If you don't pass the connection resource returned by mysql_connect() to subsequent mysql_* functions calls, php assumes the last successfully established connection. You shouldn't rely on that; better pass the link resource to the functions. a) If you ever have more than one connection per page you must pass it anyway. b) If there is no valid db connection the php-mysql modules tries to establish the default connection which is usually not what you want; it only takes up more time to fail ..again.
<?php
define('DEBUGOUTPUT', 1);
$mysql = mysql_connect("localhost","root","root");
if ( !$mysql ) {
foo('query failed', mysql_error());
}
$rc = mysql_select_db("bib", $mysql);
if ( !$rc) {
foo('select db', mysql_error($mysql));
}
$id = "12";
$titlu = "Joe";
$query = "INSERT INTO carte SET id='$id', titlu='$titlu'";
$result = mysql_query($query, $mysql);
// Display an appropriate message
if ($result) {
echo "<p>Product successfully inserted!</p>";
}
else {
foo("There was a problem inserting the Book!", mysql_error($mysql), false);
}
mysql_close($mysql);
function foo($description, $detail, $die=false) {
echo '<pre>', htmlspecialchars($description), "</pre>\n";
if ( defined('DEBUGOUTPUT') && DEBUGOUTPUT ) {
echo '<pre>', htmlspecialchars($detail), "</pre>\n";
}
if ( $die ) {
die;
}
}
try this to connect to database:
$mysqlID = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD) or die("Unable to connect to database");
mysql_select_db(DB_DATABASE) or die("Unable to select database ".DB_DATABASE);
also, try this as your insert query:
$query = "INSERT INTO carte (id, title) values ('".$id."', '".addslashes($titlu)."')
$result = mysql_query($query) or die(mysql_error());
By using die(), it will tell you where it has failed and why