SQLSTATE[42000] [1226] User has exceeded the 'max_user_connections' resource - mysql

in my website I am trying to make asynchronous calls to my database with jquery ajax function at least 100 times at the same time in a for loop and after some queries (definitely more than 30) I get the error:
SQLSTATE[42000] [1226] User '***' has exceeded the
'max_user_connections' resource (current value: 30)
but I am using a shared hosting and they say I/they cannot change the max_user_connections value to a higher number.
Now, I have no idea how to solve this problem. Is there anyone who knows a way? Thank you.
Edit: I have a website for classification of species/taxonomy and I want to show this in a sunburst chart but there are more than 65K species and it is hard to draw all chart. To achieve this, I made this chart clickable and when an user clicks, new elements are drawn by the response of ajax call.
For simplification, I do not include the lines that I define the variables.
JavaScript:
$.when(info(domain,name)).done((response)=>{
try {
layer_info = jQuery.parseJSON(response)
}catch (error) {
console.log(response)
console.log(error)
}
for (let i = 0; i < layer_info.size; i++) {
$.when(info(child_domain,child_name)).done((resp)=>{
try {
child_info = jQuery.parseJSON(resp)
} catch (e) {
console.log(resp) // I get mentioned error from info.php on console from this line.
console.log(e)
}
})
}
})
Function info makes the ajax call and returns the response.
function info(b,i){
return $.ajax({
url: "info.php",
method:"POST",
data:{domain:b,name:i},
dataType: "text",
})
}
info.php:
try{
$timezone = "+3:00";
$db=new PDO('mysql:host=localhost;port=3306;dbname=***;charset=utf8','***', '***');
$db->exec("SET time_zone = '{$timezone}'");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}catch(PDOException $e){
echo $e->getMessage(); // this line generates the error
}
try{
$name = $_POST["name"];
$domain = $_POST["domain"];
$count_query = $db->prepare("SELECT COUNT(*) FROM table WHERE $domain=?");
$count_query->execute(array($name));
$count_result = $count_query->fetchColumn();
$query = $db->prepare("SELECT * FROM table WHERE $domain=? GROUP BY $sub");
$query->execute(array($name));
while($results = $query->fetch(PDO::FETCH_ASSOC)){
array_push($nodes,$results);
}
$data['spec_size'] = $count_result;
$data["size"] = count($nodes);
$data["childs"] = $nodes;
echo json_encode($data);
}catch (\Throwable $th) {
echo $th;
}

Related

MySQL Node JS: select query results to array and use this array in other functions

I need to get user information and use it in all file but when i save it to array or session array - it show undefined.
connection.query('SELECT * FROM users WHERE username = ? OR email = ? AND password = ?', [login, login, password], function (err, results) {
if (results.length > 0) {
req.session.username = results[0].username;
req.session.email = results[0].email;
req.session.password = results[0].password;
req.session.premium = results[0].premium;
req.session.created_at = results[0].created_at;
} else {
console.log("Error!");
}
});
The arrays and sessions are always undefined...
req is a function variable/public variable I assume. connection.query is asynchronous. Callbacks are always asynchronous, and every REST API is.
Asynchronous basically allows the function callbacks to run together with the next lines of code.
The reason why req isn't being returned any value is because the req's value gets printed out first before it's actually being assigned within the function.
If you would like to add everything to req, either do sth like:
someFunctionYouHaveCreated: (req,res,type) => {
connection.query('SELECT * FROM users WHERE username = ? OR email = ? AND password = ?', [login, login, password], function (err, results) {
if (results.length > 0) {
req.session.username = results[0].username;
req.session.email = results[0].email;
req.session.password = results[0].password;
req.session.premium = results[0].premium;
req.session.created_at = results[0].created_at;
} else {
console.log("Error!");
}
DoSomething(req);
});
}
DoSomething: (req) => {
//Do something
}
Or, create a promise, and run the function based on promise. Use promise.all to assign value: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all, but I don't think you need such level of complexity.

How to create simply REST API Login?

I've trying to create login code in REST Server and while I use POSTMAN to check it, the output always show HTTP_BAD_REQUEST(Login Failed). The code is ignoring security.
I use REST from https://github.com/chriskacerguis/codeigniter-restserver
This is My Controller
public function index_post(){
$data_memb = array(
'id_member'=>$this->post('id_member'),
'password'=>$this->post('password')
);
$result = $this->Member_model_api->loginMember($data_memb);
if ($result == TRUE) {
$this->response([
'status' => true,
'message' => 'Login Successfull'
], REST_Controller::HTTP_OK);
} else {
$this->response([
'status' => false,
'message' => 'Login Failed'
], REST_Controller::HTTP_BAD_REQUEST);
}
}
}
This is My Model
public function loginMember($data_memb)
{
$sql = 'SELECT * FROM member WHERE id_member = ?';
$binds = array($data_memb['id_member']);
$query = $this->db->query($sql, $binds);
if ($query->num_rows()>0) {
$rw_password = $query->result();
if (password_verify($data_memb['password'],
$rw_password[0]->password)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I expect the output is HTTP_OK(Login Successfull), or if you have more reference code, please tell me. Thanks for your help.
Since you are using POST method, you should use form-data while sending request.
I assume there may be some re-formatting issue on the server-side which might be preventing your login functionality to get verified.
Try printing both variables on the server-side and view the output.
var_dump($data_memb)
Nothing needs to send urlencoded in POST request.
Try changing the request type and see, this will work.

How to process incoming JSON data from connected IoT device

I need some support with a personal project Im working on. I have a connected device which sends JSON data at a defined interval (every 1 min / 5 min/ 15 mins etc) to a specific IP address on port 8080.
The JSON that is sent is in following format:
{
"MeterSN": “1234”,
"Status": ###,
“Variable1”: “###”,
"Variable2”: “###”,
"Variable3”: ###
}
I have started building a PHP Rest API to process this data but am somehow not able to save the to mySQL.
Here is what I have so far:
meterdata.php
class MeterDataInput{
private $conn;
private $table_name = "meterdata";
public $MeterSN;
public $StatusA;
public $Variable1;
public $Variable2;
public $Variable3;
public function __construct($db){
$this->conn = $db;
}
}
function createMeterRecord(){
$query = "INSERT INTO
" . $this->table_name . "
SET
MeterSN=:MeterSN, Status=:Status, Variable1=:Variable1, Variable2=:Variable2, Variable3=:Variable3";
// prepare query
$stmt = $this->conn->prepare($query);
// sanitize
$this->MeterSN=htmlspecialchars(strip_tags($this->MeterSN));
$this->Status=htmlspecialchars(strip_tags($this->Status));
$this->Variable1=htmlspecialchars(strip_tags($this->Variable1));
$this->Variable2=htmlspecialchars(strip_tags($this->Variable2));
$this->Variable3=htmlspecialchars(strip_tags($this->Variable3));
// bind values
$stmt->bindParam(":MeterSN", $this->MeterSN);
$stmt->bindParam(":Status", $this->Status);
$stmt->bindParam(":Variable1", $this->Variable1);
$stmt->bindParam(":Variable2", $this->Variable2);
$stmt->bindParam(":Variable3", $this->Variable3);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
index.php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once 'config/db.php';
// instantiate MeterData object
include_once 'objects/meterdata.php';
$database = new Database();
$db = $database->getConnection();
$meterdata = new MeterDataInput($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(!empty($data->MeterSN)){
// set product property values
$meterdata->MeterSN = $data->MeterSN;
$meterdata->Status = $data->Status;
$meterdata->Variable1 = $data->Variable1;
$meterdata->Variable2 = $data->Variable2;
$meterdata->Variable3 = $data->Variable3;
// create the meter data entry
if($meterdata->createMeterRecord()){
// set response code - 201 created
http_response_code(201);
// update the status
echo json_encode(array("message" => "Data record was added"));
}
// if unable to create the record
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to add record."));
}
}
// data is incomplete
else{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to create data record. Data is incomplete."));
}
Obviously i also have config.php and db.php
I am not sure where i am going wrong, however I am not able to see the records popupate within mySQL.

error message in google api in cakephp3

My function below to access googleapi doesnt work all the time in cakephp3. If I run the same function with the same parameters it works mostly but can fail with this error message below. This message does not make sense because if i run the function again it will work . The function is only being run a few times a day only and as i said it works fine most of the time.
[
'error_message' => 'You have exceeded your daily request quota for this API. We recommend registering for a key at the Google Developers Console: https://console.developers.google.com/apis/credentials?project=_',
'results' => [],
'status' => 'OVER_QUERY_LIMIT'
]
private function calculate_test($suburb=null,$state=null){
$state='VIC';
$country='AU';
if ( $suburb==null){
return 0;
}
$address = $suburb.','.$state.','.$country;
$array = array();
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($address )."&sensor=false";
$result_string = file_get_contents($url);
$geo2 = json_decode($result_string, true);
debug('$geo2');
debug($geo2);
if ($geo2['status'] == 'OK') {
if (isset($geo2['results'][0]['geometry']['location']['lat']) && isset($geo2['results'][0]['geometry']['location']['lng'])){
$lat=$geo2['results'][0]['geometry']['location']['lat'];
$long=$geo2['results'][0]['geometry']['location']['lng'];
$array = array('suburb'=> $suburb ,'lat'=> $lat, 'long'=> $long);
}
}
return $array;
}
in layout i have the entry
<script type="text/javascript" src="https://maps.google.com.au/maps/api/js?sensor=false"></script>
the api docs say this is a problem with not getting a key

TypeError: Cannot read property 'name' of undefined

When i type the username which is there in Table "fun" i am not facing any error but when i type wrong name that is the name which is not there in the table am facing error this is the error and code is attached below.
app.post('/Fu',function(req,res,next){
var username = req.body.uname;
var password = req.body.pwd;
con.query('SELECT name FROM fun WHERE name = "' + username +'" ',function(err, result,fields) {
var w = result[0].name;
if( username == w ){
console.log("login successful");
}
else{
console.log("login not successful");
}
}
});
res.send("success1");
});
can someone please help with the error.
This error is probably related to the fact that, when username is not present in the table, result will be set to and empty array []. That means that it has no elements at all, so result[0] is undefined.
Make sure to check for that before trying to get result[0].name.
Also, I would suggest you a few things:
1) Add error checking before anything else;
2) You do not need to check if the name is equal to the result. The query you wrote will only return entries that already match that requirement;
3) Send the responses inside the callback function, otherwise, the user will get the "success1" answer before the query has even finished executing.
Here follows the resulting code:
app.post('/Fu',function(req, res, next){
var username = req.body.uname;
var password = req.body.pwd;
con.query('SELECT name FROM fun WHERE name = "' + username +'"', function(err, result,fields) {
if (err) {
response.sendStatus(500);
return;
}
if (result.lenght > 0) {
res.send('Login was successful');
} else {
res.send('Login was not successful');
}
});
});
Your problem is here:
var w = result[0].name;
Because the result set at [0] doesn't exist (query came back with nothing). you are trying to get the name value from something that is undefined.
Do something like this:
var w
if (result[0]) {
w = result[0].name
} else {
//your logic to handle this scenario
}
That assumes that whatever db querying library you use will return an array, even if empty. If it returns undefined instead of an empty array, your if statement would need to look more like: if (result && result[0])