simplifying 6 mysql queries in 1 page - php

I've got a script that opens 6 MySQL queries in 1 php page. here's the script:
if(!isset($_SESSION["name"]) || empty($_SESSION["name"])) {
header("Location: http://www.google");
die();
} else {
$servername = "localhost";
$username = "user";
$password = "123";
// Create connection
$conn = new mysqli($servername, $username, $password);
$conn2 = new mysqli($servername, $username, $password);
$conn3 = new mysqli($servername, $username, $password);
$conn4 = new mysqli($servername, $username, $password);
$conn5 = new mysqli($servername, $username, $password);
$conn6 = new mysqli($servername, $username, $password);
if ($conn4->connect_error) {
die("Connection failed: " . $conn4->connect_error);
}
$sql4 = "SELECT * FROM tableT WHERE date(ftdate) = curdate()";
$result4 = $conn4->query($sql4);
$row4 = $result4->fetch_assoc();
$conn4->close();
date_default_timezone_set("Asia/Kuala_Lumpur");
if ($result4->num_rows < 1) {
if ($conn3->connect_error) {
die("Connection failed: " . $conn3->connect_error);
}
$date = date("Y-m-d");
$sql3 = 'INSERT INTO tableT (`id`, `date`) VALUES (Null, "' . $date . '")';
if ($conn3->query($sql3) === TRUE) {
header("Location: http://google.com");
die();
} else {
echo "Error: " . $sql3 . "<br>" . $conn3->error;
}
$conn3->close();
} Else {
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($conn2->connect_error) {
die("Connection failed: " . $conn2->connect_error);
}
$sql = "SELECT * FROM tableB WHERE something = '0'";
$sql2 = "SELECT * FROM tableP WHERE id=1";
$result = $conn->query($sql);
$conn->close();
$result2 = $conn2->query($sql2);
$row2 = $result2->fetch_assoc();
$conn2->close();
if ($conn5->connect_error) {
die("Connection failed: " . $conn5->connect_error);
}
$month = date("m");
$sql5 = "SELECT * FROM tableB WHERE month(date) = '" . $month . "' AND something = '1' ORDER BY fid";
$result5 = $conn5->query($sql5);
if ($result5->num_rows > 0) {
$x = 1;
$monthlyt = 0;
$y = 0;
$dailyt = 0;
$day = date("Y-m-d");
while($row5 = $result5->fetch_assoc()) {
$monthlyt = $row5[ftotal] + $monthlyt;
$x = $x + 1;
$dbdate = date("Y-m-d", strtotime($row5[fdate]));
if ($dbdate == $day) {
$y = $y + 1;
$dailyt = $row5[total] + $dailyt;
}
}
$damount = ($y / $row2[something]) * 100;
$dtotal = ($dailyt / $row2[some]) * 100;
$mtotal = ($monthlyt / $row2[blah]) * 100;
}
$conn5->close();
if ($conn6->connect_error) {
die("Connection failed: " . $conn6->connect_error);
}
$sql6 = 'UPDATE tableT SET something="' . $y . '", some="' . $blah. '" WHERE tdate="' . $day . '"';
if ($conn6->query($sql6) === TRUE) {
//done
} else {
echo "Error: " . $sql6 . "<br>" . $conn6->error;
}
$conn6->close();
}
}
this page loads a dashboard showing a few different tables and some average response time calculations.
it was working previously, but I got an error saying "website redirected you too many times" Try clearing your cookies. ERR_TOO_MANY_REDIRECTS from chrome today.
So i'm thinking, is there a way I can simplify this? or would this lead to errors?

Related

How can fetch a variable in sql to php according to post id? [duplicate]

I am getting an error "Fatal error: Call to undefined function fetch_assoc()". Can you please advise on how I should proceed?
The code is mentioned below
$servername = "localhost";
$username = "s";
$password = "j";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "select idnew_table, new_tablecol from new_schema.new_table;";
$result = $conn->query($sql);
$r = count($result);
if ($result['num_rows'] != 10) {
while($row = $result[fetch_assoc()]){
echo "id: " . $row["idnew_table"]. " - Name: " . $row["new_tablecol"];
}
} else {
echo "0 results";
}
$conn->close();
This line:
while($row = $result[fetch_assoc()]){
should be:
while($row = $result -> fetch_assoc()){

Creating multiple SQL Data from For-loop

I am trying to add random x and y values to a MySQL database but strangely it only seems to ever add one value. I was looking at many of the other posts of similar issues on Stackoverflow and it just seemed they did not have query within the loop was the common issue. I do have the query in the loop and am unsure why it is still not working.
Please see my code below:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
I edited your for loop to look something like this, and it worked perfectly fine for me.
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y) VALUES ('$x', '$y')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Successfully created record " . $i;
} else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
ob_start();
ob_flush();
flush();
usleep(001000);
ob_flush();
flush();
}
it Delay's the loop by just a little like a fifth of a second in total. The reason I have delayed the iteration is because your database might have a limit on how many queries can be sent within a time frame. It works for me let me know if it works for you.
Create the values array in the for loop, then use implode to build the query outside the loop.
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myTable";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_errno) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO data (x, y) VALUES ";
$values = [];
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$values[] = "($x, $y)";
}
$query = $sql . implode(",", $values) . ";";
$r = $conn->query($query);
if ($r) {
echo "New records created successfully";
} else {
echo "Error: " . $query . "<br>" . $conn->connect_error;
}
$conn->close();
You are just running a single query for each loop. No need for multi query
for ($i = 0; $i <= 100; $i++){
$x = rand(0,20);
$y = rand(0,200);
$sql = "INSERT INTO data (x, y)"
$sql .= "VALUES ($x, $y);";
//mysql_query($sql);
if (mysqli_query($conn,$sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

PHP Fatal error: Could not queue new timer in Unknown on line 0

I write a simple web application for my compnay that can let user log in to arrange their work time. Besides, user can also view the report of he's or she's attandence that I use ajax to callback from java.jar. (We use java to analyze)I use Xampp to set up the server in virtual machine HyperV and it can run successfully at the begining but after twenty hours or more than one day it won't let anyone to log in.
I open the error.log shows that :
PHP Fatal error: Could not queue new timer in Unknown on line 0
. . . and than:
PHP Warning: mysqli_connect(): (HY000/2002): Unknown Error
I don't understand what can cause that happend and how to solve it.
I alreday know is when I restarted the apache server, it can still be used till that error happened.
My System Enviroment :
win7 64 bit HyperV
xampp Apache/2.4.18, php/7.0.6, mysql/ 5.1
Here is my code:
mysql_start.php
<?php
header("Content-Type:html;charset=utf-8");
$servername = "127.0.0.1";
$username = "root";
$password = "cc1234";
$dbname = "cc_tw000427";
$conn = null;
try {
$conn = new mysqli($servername, $username, $password, $dbname);
} catch (Exception $e) {
$error_message = "Connect Error (" .$conn->connect_errno ." )" . $conn->connect_error;
error_log($error_message, 3, "php_error_log");
header("location:login.php?err=$e");
}
$conn->set_charset("utf-8");
$strDBColLoingAccount = "AccountID";
checklogin.php
session_start();
include_once("mysql_start.php");
$yid = trim(filter_input(INPUT_POST, "yid"));
$passd = trim(filter_input(INPUT_POST,"passd"));
$strSql = "SELECT acc.*, b.String_10_1 FROM basicstoreinfomanageacc_sub acc,basicstoreinfo b
WHERE acc.$strDBColLoingAccount ='$yid' AND acc.String_50_1 = b.String_50_1";
$result = $conn->query($strSql);
$n = $result->num_rows;
if ($n == 0) {
header("Location:../desktop/login.php?err=1");
echo "Error 1";
exit();
}
while ($row = $result->fetch_assoc()) {
$passd_right = $row["AccountPwd"];
$user_id = $row["AccountID"];
$user_name = $row["AccountName"];
$user_dep_id = $row["String_10_1"];
$user_dep = $row['String_50_1'];
}
$result->close();
if (($passd_right == "") || ($passd_right == NULL)){
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
header("location:newpwd.php");
exit();
}
if ($passd == $passd_right) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
$_SESSION['loginOK'] = 'yes';
$_SESSION['year_i'] = date('Y',time());
$_SESSION['year_f'] = date('Y',time());
$_SESSION['month_i'] = date('m',time());
$_SESSION['month_f'] = date('m',time());
$_SESSION['day_i'] = date('d',time());
$_SESSION['day_f'] = date('d',time());
$_SESSION['Hour'] = date('Y-m-d G:i:s',strtotime('+6 hour'));
$_SESSION['user_dep_id'] = $user_dep_id;
$_SESSION['user_dep'] = $user_dep;
header("Location:../desktop/Punch.php");
} else {
header("Location:../desktop/login.php?err=1");
}
$conn->close();
?>
Next two *.php files are used to receive the post from the web.
The select.php is used to select the data from mysql than output in html tag.
The save.php is used to save the data post from web.
select.php
<?php
session_start();
include_once '../control/mysql_start.php';
$strYear = $_POST['year'];
$strMonth = $_POST['month'];
$strDay = $_POST['day'];
.
.//some codes
.
$strSql = "SELECT * FROM basicemploymentinfo bei WHERE bei.BelongStore = '". $_SESSION['user_dep']."'".
"AND ((bei.datetime_2 is null AND bei.datetime_3 is null) OR (bei.datetime_2 is null AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 is null)" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))) "
."AND bei.Active ='Y'";
$EmpId = array();
$EmpName = array();
if ($result = $conn->query($strSql)) {
while($row = $result->fetch_assoc()) {
array_push($EmpId, $row['String_20_1']);
array_push($EmpName, $row['String_20_2']);
.
.//some codes
.
}
}
$Emp = array_combine($EmpId, $EmpName);
$strSql = " SELECT Distinct date_format(DateTime_1, '%e') as date, AutoCheck
FROM hrotcheck
WHERE date_format(DateTime_1, '%Y-%m-%d') = '$newformat'
AND AutoCheck = 'C'
AND String_20_1 IN ($array_emp_id)";
if ($result = $conn->query($strSql)) {
$n = $result->num_rows;
if ($n > 0) { $checkboxVerify = 'C';}
}
$result->close();
foreach ($Emp as $EId => $EName)
{
.
.//some codes
.
$strSql = "SELECT RegularM_1, RegularM_2, FORMAT(OT_3, 1) as OT_3, TOM, TOTM, Notes, AutoCheck FROM hrotcheck where string_20_1 = '" . $EId . "' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result = $conn->query($strSql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$RegularM_1 = $row['RegularM_1'];
$RegularM_2 = $row['RegularM_2'];
$OT3 = $row['OT_3'];
$tom = $row['TOM'];
$totm = $row['TOTM'];
$notes = $row['Notes'];
}
}
$result->close();
.
.//I did a lot of SQL select and use that to create htmltable
.
$output .= '
<tr data-table="sub">
<td>'.$row['string_20_1'].'</td>
<td>'.$row['string_20_2'].'</td>
.
.//<td>...</td>
.
<td class="'.$condition16.'">'.$notes.'</td>
<td class="'.$condition17.'"></td>
</tr>
';
}
.
.//some codes
.
$strSql01 = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$row['string_20_1']."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result01 = $conn->query($strSql01);
if ($result01->num_rows > 0) {
while ($row01 = $result01->fetch_assoc()) {
.
.//some codes
.
}
}
$result01->close();
.
.//some codes
.
$result->close();
$conn->close();
echo $optionUse.'?'.$checkboxVerify.'?'.$output.'?'.$hasCheckDate;
?>
save.php
<?php
session_start();
include_once '../control/mysql_start.php';
$arrayObjs = $_POST;
.
.//some codes
.
$msDanger = '';
foreach($arrayObjs as $array)
{
foreach($array as $row)
{
$UserId = $row['UserId'];
$UserName = $row['UserName'];
.
.//some codes
.
$strSql = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
$result = $conn->query($strSql);
if( $result->num_rows > 0) {
if ($table == 'main') {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1', String_Assist01 ='$assist_1',String_Assist02='$assist_2' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
} else {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
}
$result = $conn->query($strSql);
} else {
$strSql = "INSERT INTO manufacturejobschedulingpersonal (string_20_1,string_20_2,YM,DateTime_1,String_10_1,String_Assist01,String_Assist02)".
"VALUES ( '$UserId', '$UserName', '$YM', '$DateTime_1', '$String_10_1','$assist_1','$assist_2')";
$result = $conn->query($strSql);
}
.
.//A lot of sql CRUD
.
}
}
$conn->close();
$last_line = exec('java -jar C:/CCERP/ChainCodeERP/ExtraModule/HRMultiOTCheck/HRMultiOTCheck.jar -ssa '.$javaDate.' ' .$javaDepId, $return_var);
echo 'Updated';
?>

PHP select data from database

<?php
$servername = "localhost";
$username = "root";
$password = "william";
$dbname = "camping";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT fnavn,enavn,epost,tlf FROM knr ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["fnavn"]. " - Name: " . $row["enavn"]. " " . $row["epost"]. "ire: " . $row["tlf"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Tried it, and it doesnt work, anyone who knows why? It's something wrong with the second if statement I think
You would need to join the tables:
SELECT * FROM produkt
LEFT JOIN produkttype ON (produkt.ptype = producttype.ptype)
WHERE utleid="No"

Select, Insert and Update MySQL table PHP script not working

I wrote the following code:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
echo $result;
if ($result > 0) {
$result = $result + 1;
$sql2 = "UPDATE Eshop SET quantity = $result WHERE id = $insert";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ($insert, 1)";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
?>
What I want this script to do is select the quantity where the id is $insert and then if quantity > 0, add 1 to the quantity and update the quantity, if not insert the id and quantity = 1 into the table. The table has only two fields id(VARCHAR(32)) and quantity(DECIMAL(8,1)). I tried to do it more general in order to help as many people as possible. Could you please help me? Thanks in advance. NOTE: When I run the script in the browser(after uploading it to the server with the correct username,domain etc.) nothing shows up and I dont even get an error in the console.
You need to extract the result of your query and loop through each row:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$sql2 = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($sql2) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($sql3) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
}
?>
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
//check if particular record exists or not
$count=mysql_num_rows($result);
if($count>0) // if records exists for the particular id
{
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$update = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($update ) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $update . "<br>" . $conn->error;
}
} else {
$insert = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($insert ) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert . "<br>" . $conn->error;
}
} // else qty is <=0
} //end while
}
else {
echo "Records do not exists for that particular id";
}
?>

Categories