I kept commenting parts of my PHP script till this is what I ended up with. This thing creates about 200 to 300 concurrent connections in under a minute to the SQL ip (checked from the gateway) and I don't understand why.
Shouldn't closing the SQL connection end the communication between the servers?
The php script is being called once a second via JavaScript, I'm the only user on the website.
PHP implementation of the sock (taken from the net, fclose() added as that's how I read socks are closed)
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM `users`");
$num_rows = mysqli_num_rows($result);
$result = mysqli_query($con,"SELECT * FROM `users` WHERE admlevel>0");
$num_admrows = mysqli_num_rows($result);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM jbchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$jbchat = $jbchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM frchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$frchat = $frchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM drchat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$drchat = $drchat . $data[$i] . "<br>";
}
unset($data);
$data = array();
$i=1;
$result = mysqli_query($con,"SELECT * FROM cschat ORDER BY id DESC LIMIT 7");
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['string'];
$i=$i+1;
}
for($i=7;$i>0;--$i)
{
$cschat = $cschat . $data[$i] . "<br>";
}
$today = getdate();
$date = $today['mday'] . "/" . $today['mon'] . "/" . $today['year'];
if($today['minutes']>9)
$time = $today['hours'] . ":" . $today['minutes'];
else
$time = $today['hours'] . ":0" . $today['minutes'];
$sqlx = 'SELECT * FROM notifications WHERE username=? ORDER BY id DESC LIMIT 5';
# Prepare statement
$stmt = $con->prepare($sqlx);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sqlx . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
$stmt->execute();
$res = $stmt->get_result();
while($row = $res->fetch_assoc())
{
if($row['read']==0)
$nnumber = $nnumber+1;
$notifications = $notifications . "
<li>
<a href=\"#\" onclick=\"invisphp2('http://r4ge.ro/php/readnotif.php?notifid=" . $row['id'] . "')\">
<i class=\"fa fa-warning danger\"></i>" . $row['text'] . "
<br>" . $row['date'] . "
</a>
</li>";
}
$result = mysqli_query($con,"SELECT * FROM chat ORDER BY id DESC LIMIT 30");
$data = array();
$i=1;
while($row = mysqli_fetch_array($result))
{
$data[$i] = $row['name'] . ": " . $row['msg'];
$i=$i+1;
}
for($i=30;$i>0;--$i)
{
$lchat = $lchat . $data[$i] . "<br>";
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
Edit: after listening to a comment that's now deleted, I removed every single query except the first one, so this code is now being ran, the connections still rocketed to 150 in 20-30 seconds.
<?php
$cookie="tD2h6";
$data = $_COOKIE[$cookie];
parse_str($data, $output);
$name = $output['name'];
$pass = $output['pass'];
$con=mysqli_connect("89.33.242.99","global","changeme","global");
$sql = 'SELECT * FROM `users` WHERE `username`=?';
# Prepare statement
$stmt = $con->prepare($sql);
if($stmt === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->errno . ' ' . $con->error, E_USER_ERROR);
}
# Bind parameters. Types: s = string, i = integer, d = double, b = blob
$stmt->bind_param('s', $name);
# Execute statement
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
if($row['password']===$pass && !empty($pass))
{
$hisusername = $name;
$hiscredits = $row['credits'];
$hiseuro = $row['euro'];
}
else
{
$hisusername = "Guest";
$hiscredits = "0";
$hiseuro = "0";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo json_encode(array(
"registered" => $num_rows,
"admins" => $num_admrows,
"time" => $time,
"date" => $date,
"nnumber" => $nnumber,
"notifications" => $notifications,
"lchat" => $lchat,
"hisusername" => $hisusername,
"hiscredits" => $hiscredits,
"hiseuro" => $hiseuro
));
mysqli_close($con);
?>
I know this will make me look very bad.
Unfortunately there is nothing bad in this particular code.
The problem was at a much deeper level in the site's framework, and the above code being the homepage, lead me to think it was the source of the problem.
To #developerwjk , the answer is no, combining procedural and object oriented implementations has no effect whatsoever on the functionality of mysqli, it works great.
The culprit: lack of mysqli_close() at the end of every single PHP that creates a connection
Don't trust the documentation when it says the connection is closed on script end, put it there just to be safe.
Related
What is the best way to stop the script if there are no results????
The Upload the file that is created to a vender but I don't need to creat a file if there is no results,
I have a second question what is the best way to run this every hour between 8 am and 6 pm Monday through Friday?
I found a lot of information on this if using MySQL but we are using Microsoft SQL Server.
Thanks for the help!
<?php
$connect = odbc_connect("removed");
if (!$connect) {
exit("Connection Failed: " . $connect);
}
$gr_total = 0;
$gr_count = 0;
$sql = "
SELECT distinct
ltrim(rtrim(SO.ompCustomerOrganizationID))as customer
,ltrim(rtrim(left(cmoName,30))) as name
,left(ltrim(rtrim(cmoAddressLine2)),30) as address1
,ltrim(rtrim(cmoCity)) as city
,ltrim(rtrim(cmoState)) as state
,ltrim(rtrim(cmoPostCode)) as postal
, ltrim(rtrim(REPLACE(REPLACE(REPLACE(cmoPhoneNumber, '(', ''), ')', ''), '-', ''))) as phone
FROM m1_kf.dbo.SalesOrders SO
LEFT JOIN m1_kf.dbo.Organizations ON cmoOrganizationID = SO.ompCustomerOrganizationID
WHERE ompCreatedDate >='06-11-2017' and ompPaymentTermID in ('CN30','CTN30')
and UOMPSCHEDULENUMBER !=1 and ompOrderTotalBase > 1
";
$sql2 = "
select
ltrim(rtrim(ompCustomerOrganizationID)) as cust
,ltrim(rtrim(ompSalesOrderID)) as orderid
, right('00000000'+cast(cast(round(ompOrderTotalBase,0)as int) as varchar(8)),8) as num
,REPLACE(CONVERT(VARCHAR(10), ompRequestedShipDate, 1), '/', '') as reqship
,'030' as terms
,REPLACE(CONVERT(VARCHAR(10), ompRequestedShipDate, 1), '/', '') as ship
FROM m1_kf.dbo.SalesOrders SO
WHERE ompCreatedDate >='06-11-2017' and ompPaymentTermID in ('CN30','CTN30')
and UOMPSCHEDULENUMBER !=1 and ompOrderTotalBase > 1
order by SO.ompCustomerOrganizationID
";
$result = odbc_exec($connect, $sql);
if (!$result) {
exit("Error in SQL");
}
$mycount = 0;
$tradestyle = ' ';
$address2 = ' ';
$my_file = 'cit_order_upload.co';
$handle = fopen($my_file, 'w+') or die('Cannot open file: ' . $my_file);
while ($row = odbc_fetch_array($result)) {
$record_type = 'A';
$cit_cust_id = '1234';
$cust_num = $row['customer'];
$name = $row['name'];
$address = $row['address1'];
$city = $row['city'];
$state = $row['state'];
$postal = $row['postal'];
$phone = $row['phone'];
fprintf($handle, "%-4s%-2s%-1s%-15s%-30s%-30s%-30s%-17s%-2s%-9s%-10s", $cit_cust_id, $tradestyle, $record_type, $cust_num, $name, $address, $address2, $city, $state, $postal, $phone . "\n");
$mycount = $mycount + 1;
}
$results = odbc_exec($connect, $sql2);
if (!$results) {
exit("Error in SQL");
}
$mycount2 = 0;
$space1 = ' ';
$space6 = ' ';If the first while loop does not have any results then stop the script
$space12 = ' ';
$today = date("mdy");
echo "<table><tr>";
echo "<th>CustID</th>";
echo "<th>OrderId</th>";
echo "<th>Amount</th>";
echo "<th>TotalAmount</th>";
while ($row = odbc_fetch_array($results)) {
$client = '1234';
$trade = ' ';
$record_ty = 'R';
$cust = $row['cust'];
$orderid = $row['orderid'];
$num = $row['num'];
$reqship = $row['reqship'];
$terms = $row['terms'];
$ship = $row['ship'];
$mycount2 = $mycount2 + 1;
$gr_total = $gr_total + $row['num'];
$tradestyle = '99';
$custnum = '999999999999999';
$record = 'S';
$recordtype = '999999T999999999999999';
fprintf($handle, "%-4s%-1s%-1s%-15s%-22s%-8s%-1s%-6s%-3s%-6s", $client, $trade, $record_ty, $cust, $orderid, $num, $space1, $reqship, $terms, $ship . "\n");
echo "<tr><td>$cust </td>";
echo "<td> $orderid </td>";
echo "<td> $num </td>";
echo "<td> $gr_total </td></tr>";
}
fprintf($handle, "%-4s%-2s%-1s%-15s%06d%06d%-6s%012d", $client, $tradestyle, $record, $custnum, $mycount, $mycount2, $space6, $gr_total);
fprintf($handle, "\n");
fprintf($handle, "%-22s%06d%06d%-6s%012d%-12s%-6s", $recordtype, $mycount, $mycount2, $space6, $gr_total, $space12, $today);
fclose($handle);
?>
You already have this stop condition if query is unsuccessful, for handling case with no results modify it like below:
if (!$result) {
exit("Error in SQL");
}
if (0 === odbc_num_rows($result)) {
exit("No results");
}
Check the docs for OBDC_num_rows.
About your secondary question - cron utility is probably the most popular way to schedule jobs. Your crontab string should be like this:
* 8-18/1 * * 2,3,4,5 yourscript.php
i have little problem here, i want to generate some data to specific JSON format from Mysql using PHP, this is my PHP code
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
// echo(json_encode($names));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
?>
With this code, the result was
[
[1478616679000, 1478616677000, 1478616675000, 1478616673000, 1478616671000],
[28.4126, 28.5361, 28.4126, 28.4126, 28.2891]
]
Yes, that is valid JSON but, i want to use this JSON for chart in highcharts.com, so i need the JSON format like this
[
[1257811200000, 29.00],
[1257897600000, 29.04],
[1257984000000, 28.86],
[1258070400000, 29.21],
[1258329600000, 29.52],
[1258416000000, 29.57],
[1258502400000, 29.42],
[1258588800000, 28.64],
[1258675200000, 28.56],
[1258934400000, 29.41],
[1259020800000, 29.21],
[1259107200000, 29.17],
[1259280000000, 28.66],
[1259539200000, 28.56]
]
Gladly if someone can help me, i'm stuck for a days try to solving this issue
If you want the code like that, you must fix the code:
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$text[] = (float)$row['ai0_hist_value'];
$date[] = strtotime($row['meas_date'])*1000;
}
//$data[0] = $names;
$data1 = $date;
$data = $text;
$data2 = array($data1, $data);
//$data[2] = $text;
echo (json_encode($data2));
must be something like this:
while($row = $result->fetch_array()){
$rows[] = array(
(float)$row['ai0_hist_value'],
strtotime($row['meas_date'])*1000);
}
echo (json_encode($rows));
You were saving in $data2 an array with two arrays, the text and the data. You must save a row for each pair of 'text' and 'data'.
Could construct the formatted series data to begin with like below:
<?php
/*
Get data from the mysql database and return it in json format
*/
//setup global vars
$debug = $_GET['debug'];
$format = $_GET['format'];
if($format=='json'){
header("Content-type: text/json");
}
$db = new mysqli('localhost', root, 'kudanil123', 'PT100', 3306);
if (mysqli_connect_error()) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
if ($debug == 1) {echo 'Success... ' . $db->host_info . "\n";}
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
if ($result = $db->query($sql)) {
if ($debug == 1) {echo "fetched data! <br/><br/>";}
while($row = $result->fetch_array()){
$rows[] = $row;
}
foreach($rows as $row){
$seriesData[] = [ strtotime($row['meas_date'])*1000, (float)$row['ai0_hist_value'] ];
}
echo (json_encode($seriesData));
$result->close();
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
This will generate the array you want, there is no need to do all that fiddling with the data from the database
// get data
$sql = "select meas_date,ai0_hist_value";
$sql .= " from ai0_hist";
$sql .= " where board_temp_hist_value > 30"; //filter out bad data
$sql .= " group by 1";
$sql .= " order by meas_date desc"; //highcarts requires you order dates in asc order
$sql .= " limit 5;";
$rows = array();
if ($result = $db->query($sql)) {
while($row = $result->fetch_array()){
$rows[] = array(strtotime($row['meas_date'])*1000,
$row['ai0_hist_value']
);
}
}
echo json_encode($rows);
Now you will need to convert the text to float in the javascript. This is because JSON is passed as text and not any other data type, so it has to be converted, if necessary in the receiving javascript.
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';
?>
I need to migrate data within our old bug tracker (Zentrack) to our new one and the only import method I can use is to import from CSV. To do so I need the data from two tables, tickets and logs so I wrote the script below in php.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "dbuser";
$pass = "dbpass";
$db = "zentrk";
$users[1] = 'john';
$users[4] = 'sally';
$users[5] = 'nick';
$users[6] = 'ralph';
$r = mysql_connect($host, $user, $pass);
if (!$r) {
echo "Could not connect to server\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
echo mysql_get_server_info() . "\n";
$r2 = mysql_select_db($db);
if (!$r2) {
echo "Cannot select database\n";
trigger_error(mysql_error(), E_USER_ERROR);
}
$query_tickets = "select ZENTRACK_TICKETS.id, ZENTRACK_TICKETS.title, ZENTRACK_TICKETS.priority, ZENTRACK_TICKETS.status, ZENTRACK_TICKETS.description, ZENTRACK_TICKETS.otime,
ZENTRACK_TICKETS.type_id, ZENTRACK_TICKETS.user_id, ZENTRACK_TICKETS.system_id, ZENTRACK_TICKETS.creator_id, ZENTRACK_TICKETS.proj_key
from ZENTRACK_TICKETS
where ZENTRACK_TICKETS.status = 'OPEN'
and ZENTRACK_TICKETS.system_id in ('18', '3', '6', '1', '16', '7', '9', '4', '20')
and ZENTRACK_TICKETS.type_id not in ('1', '10', '5')";
$rs = mysql_query($query_tickets);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
} else {
echo "Query: $query executed\n";
}
$export = array();
$export[] = 'id,title,created date,priority,type,assigned,description,system,creator,project key,log1,log2,log3,log4,log5,log6,log7,log8,log9,log10
';
while ($row = mysql_fetch_assoc($rs)) {
$line = '';
$count = 0;
$line .= $row['id'] . "," . $row['title'] . "," . date('d-M-y h:m a',$row['otime']) . "," . $row['priority'] . "," . $row['type_id'] . "," . $row['user_id'] . "," . $row['description'] . "," . $row['system_id'] . "," . $row['creator_id'] . "," . $row['proj_key'] . ",";
$logs = find_logs($id = $row['id']);
foreach($logs as $log_entry) {
$line .= $log_entry.",";
$count++;
}
while($count < 10) {
$line .= ",";
$count++;
}
$export[] = $line.'
';
}
mysql_close();
// print_r($export);
$file = 'tickets.csv';
file_put_contents($file, $export);
function find_logs($ticket) {
$content = array();
$query = "select ZENTRACK_LOGS.created, ZENTRACK_LOGS.user_id, ZENTRACK_LOGS.entry
from ZENTRACK_LOGS
where ZENTRACK_LOGS.ticket_id = $ticket
and ZENTRACK_LOGS.action <> 'EDIT' ";
$rs = mysql_query($query);
if (!$rs) {
echo "Could not execute query: $query";
trigger_error(mysql_error(), E_USER_ERROR);
}
while ($row = mysql_fetch_assoc($rs)) {
$date = date('d-M-y h:m a',$row['created']);
$content[] = $date . ";" . $row['user_id'] . ";" . $row['entry'];
}
return $content;
}
?>
I'm running into two problems with this script, that I'm sure are due to me being new to PHP.
1) I need to escape out the data in $row['description'] as it contains both carriage returns and , in the text that is incorrectly breaking the output into new rows when saved to CSV. I need to save the contents of this row within " " but I'm not sure how to do so.
2) The data returned in $row['user_id'], $row['creator_id'] and $row['user_id'] within the find_logs function returns a number, which I need to find that number and replace with the corresponding string in the $users array. What's the best way to do this?
When dealing with csv files use fgetcsv and fputcsv, provide it with an array and it will handle the escaping for you.
i Have This PHP and JS Code on my web page.
<?php
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());;
$counter = 0;
// write the values from the database into the javascript array
echo "<script type='text/javascript'>";
echo "this.styleListArray = new Array();";
if ($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname'
$counter += 1;
}
}
echo("</script>");
?>
The Problem is that when i execute the page containing the code, a part of this code doesn't get executed and it just shows on the page as a simple text :
"); echo "this.styleListArray = new Array();"; if ($result) { while($row = mysql_fetch_array($result)) { echo("this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';"); // displays 'lname, fname' $counter += 1; } } echo(""); ?>
I tried to figure it out, but i couldn't get it, if you can help brothers, that would be wonderful.
Try rewriting your code like this:
include 'connect1.php';
$query = "SELECT URL FROM remontee_nlf ORDER BY URL ASC";
$result = mysql_query($query) or die (mysql_error());
$counter = 0;
// write the values from the database into the javascript array
echo <<<HTML
<script type='text/javascript'>
this.styleListArray = new Array();
HTML;
$strLine = '';
if ($result) {
while($row = mysql_fetch_array($result)) {
$strLine.= "this.nameArray[" . $counter . "] = '" . $row['URL'] . ", " . $row['user_fname'] . "';";
$counter += 1;
}
}
echo $strLine;
echo("</script>");
First of all change your queries to use mysqli or pdo connections
secondly try following code
$sql = 'SELECT URL FROM remontee_nlf ORDER BY URL ASC';
$res = mysql_query($sql, $con);
$rows = array();
while ($row = mysql_fetch_assoc($res))
$rows[] = $row['URL'];
$str = implode('", "', $rows);
$data = '["'.trim($str).'"]';
echo '<script type="text/javascript">';
echo "var data = $data;";
echo 'console.log(data)';
echo '</script>';
check you console log.
You have $result = mysql_query($query) or die (mysql_error());; change it to
$result = mysql_query($query) or die (mysql_error());
Also make sure $row['URL'] and $row['user_fname'] are available.