I am attempting to create a progress bar from numeric values within a database. I have two fields within the database, one is called 'NEXT_STEP' and the other is called 'MAX_STEPS' - When NEXT_STEP = MAX_STEPS + 1, then all the steps have been completed and the progress bar should be full (100%). These steps will happen in real time, and the NEXT_STEP will increment as a process in the background progresses. The web page displaying the progress will hopefully update along with it, so use of AJAX will be required.
To do this, I am trying to retrieve these numeric values from the database, store them to PHP variables, so I can then calculate the percentage and display a progress bar with an accurate percentage. Then, making use of AJAX and a time interval, I can call the method repeatedly to update the progress bars.
So, my questions are:
How can I retrieve a field from a database and store it to a PHP variable?
How would I go about retrieving multiple rows of data, and then selecting the relevant fields and calculating the percentage? (I assume a while loop, but not entirely certain)
I have tried to make use of oci_define_by_name() to store the fields to PHP variables.
Also, I have tried to use oci_fetch() alongside oci_result() to retrieve the relevant data from the array that is fetched when the DB is queried but to no prevail.
$sql='select * from lookout_status order by TIMESTAMP_1 DESC';
$stid= oci_parse($conn, $sql);
echo $sql;
oci_define_by_name($stid, 'NEXT_STEP', $next);
echo $next;
oci_execute($stid);
I don't get an output where I expect a value to be echoed, so I'm quite lost.
Thanks for any help provided in advance.
EDIT:
I managed to solve it - For future reference if anyone comes across this question, use oci_define_by_name() to define the values from the DB to PHP variables. Then, execute the sql query, and make use of oci_fetch() inside a while loop to retrieve the values for each row of data. You can then do whatever you need to do with the data.
Thanks for the help received.
Use oci_define_by_name() to define the values from the DB to PHP variables. Then, execute the sql query, and make use of oci_fetch() inside a while loop to retrieve the values for each row of data. You can then do whatever you need to do with the data.
$stid= oci_parse($conn, $sql);
echo $sql;
echo "<br>";
oci_define_by_name($stid, 'NEXT_STEP', $next);
oci_define_by_name($stid, 'MAX_STEPS', $max);
oci_execute($stid);
while (oci_fetch($stid)){
//Some code omitted here...
$val = round($percent, 0);
echo $val;
$prog = "<progress value='$val' max='100'></progress>";
echo $prog;
echo "<br>";
echo "<br>";
}
You use PDO class to get result set from database. And then get loop over fetched result and calculate which you want.
Related
Function render makes website 500% slow! Can anyone fix that please ?
Someone told me :
because it sends a database request on each iteration of the loop (it's not the only problem with this chunk of code but it's the most taxing one)
Yes I understand what that means. His way is:
you need to get all of the data before you start building the menu,
then you just insert the data instead of requesting more data on each
iteration
But i don't know how i must do it!
<?php
$menu_html='';
function render_menu($parent_id,$actmenuid)
{
$obj = new Database();
$con = $obj->dbconnectt();
global $menu_html;
$result=mysqli_query($con, "select * from tbl_menu where parent_id='$parent_id'");
if(mysqli_num_rows($result)==0) return;
if($parent_id==0){
$menu_html.='<ul class="topnav">';
}else{
$menu_html.='<ul>';
}
while($row=mysqli_fetch_array($result)) {
$childnum = $obj->recordcount("SELECT * FROM tbl_menu WHERE parent_id='".$row['id']."'");
if($childnum == 0){
$linkvalue='/category/'.$row['id'].'.html';
} else{
$linkvalue='#';
}
if($row['id']==$actmenuid && $actmenuid !=NULL){
$actv='class="active"';
}else{
$actv='';
}
$menu_html.='<li '.$actv.'>'.$row['title'].'';
render_menu($row['id'],$actmenuid);
$menu_html.='</li>';
}
$menu_html.='</ul>';return $menu_html;
}
if($isDsh==false){
echo render_menu(0,$actmenuid);
}
?>
Depending on how many records you have, try removing this query from inside the loop since it's running for every record on the first query.
$childnum = $obj->recordcount("SELECT * FROM tbl_menu WHERE parent_id='".$row['id']."'");
Change it a single query like this where it returns counts for each parent idea, and place it outside of the loop:
$parentcount = mysqli_query($con, ("SELECT parent_id, count(*) FROM tbl_menu GROUP BY parent_id");
There may be other issues, so please post the database structure and number of records that you're working with too.
Don't make recursive queries.
Having "more than 1000" rows is not too big. You can simply call everything from the table into php, then perform the recursive html build in php this will have a memory overhead, but far less processing overhead because you only ever make one trip to the db.
Alternatively (when your db table is prohibitively large), you should avoid gathering rows unnecessarily by adding a new column. The new column will store all "descendants" for the respective row when the row is INSERTed or update it when it is UPDATEd. Then you only need to reference this column when needing to call specific rows. In other words, do the recursive processing only once (when writing to the db) AND not when needing to display the data. This will, again, produce a finite result set in one query which can then be recursively traversed to build the desired output.
basically you need to do what #spudly has suggested.
But there is a small catch in his solution which depending on the number of the rows in yous tbl_menu table you may use a big chunk of memory to fetch all the records.
you can optimise it more with using his solution but changing the query to:
select
parent_tbl_menu.id,
count(child_tbl_menu.id) as cnt
from
tbl_menu as parent_tbl_menu
left join
tbl_menu as child_tbl_menu
on parent_tbl_menu.id = child_tbl_menu.parent_id
where
parent_tbl_menu.parent_id = ?
group by
parent_tbl_menu.id
This way you will only fetch the child records of a specific parent.
And please consider using prepared statements as your code has sql injection vulnerability.
Connect (from PHP to MySQL) only once for the entire web page.
Don't put a SELECT inside a loop if you can do all the work in a single SELECT, such as with a JOIN. (Exception: A "hierarchical" table needs the nested SELECT. Exception to the exception: MySQL 8.0 and MariaDB 10.2 can do it with a "recursive CTE".)
Don't fetch all the columns (SELECT *) when all you want it is a recordcount. Instead, SELECT COUNT(*) ... and use the number returned.
1000 of anything is probably excessive for a web page. Re-think the UI.
I am trying to figure out how to delete all ids in the database that do not exist in an array. I have been trying to use NOT IN in my query but I am not sure why it wont work when running it in a script the same way it works when I manually enter it into mysql. Here is an example.
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($array)");
$array is a list of ids from a json api. I use CURL to fetch the ids and I am trying to delete all ids in the database that do not match the ids in $array.
First I use another simple CURL script to scrape the apis and insert the ids found into the database and what I am trying to do here is basically make a link/data checker.
If the ids in the database are not found in the array when rechecking them then I want them deleted.
I thought that the query above would work perfect but for some reason it doesn't. When the query is ran from a script the mysql log shows the queries being ran as this.
Example:
DELETE FROM table WHERE id NOT IN ('166')
or this when I am testing multiple values.
DELETE FROM table WHERE id NOT IN ('166', '253', '3324')
And what happens is it deletes every row in the table every time. I don't really understand because if I copy/paste the same query from the log and run it manually myself it works perfect.
I have been trying various ways of capturing the array data such as array_column, array_map, array_search and various functions I have found but the end result is always the same.
For right now, just for testing I am using these 2 bits of code for testing 2 different apis which gives me the same sql query log output as above. The functions used are just a couple random ones that I found.
//$result is the result from CURL using json_decode
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
foreach ($result['data'] as $info){
$ids = implode_r(',', $info['id']);
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ($ids)");
}
And
$arrayLength = count($result);
for($i = 0; $i < $arrayLength; $i++) {
mysqli_query($con, "DELETE FROM table WHERE id NOT IN ('".$result[$i]['id']."')");
}
If anyone knows what is going on i'd appretiate the help or any suggestions on how to achieve the same result. I am using php 7 and mysql 5.7 with innodb tables if that helps.
It probably doesn't work because your IN value is something like this
IN('1,2,3,4');
When what you want is this
IN('1','2','3','4')
OR
IN( 1,2,3,4)
To get this with implode include the quotes like this
$in = "'".implode("','", $array)."'";
NOTE whenever directly inputting variables into SQL there is security Implications to consider such as SQLInjection. if the ID's are from a canned source you're probably ok, but I like to sanitize them anyway.
You can't mix array and string.
This works:
mysqli_query($con, "DELETE FROM table WHERE id NOT IN (".implode(',', $ids).")");
I'm working in the IT department of my company and it is my responsibility to send daily reports of the calls registered in the Call Center department. I'm new with MySQL, PHP or HTML and I'm already facing my first problems.
My objective is to run some queries in PHP and then output them in a HTML table cell. Let me be more specific. I have access to a telephone record database and I need to count the number of total calls and lost calls of every branch daily. Right now I just run 2 queries in MySQL and then copy-paste them in a .xls table.
I have the right queries, I get the right result in mysql, even in PHP I get the result posted on the webpage (kind of), but I don't know how to create a table, or how to input the result of a query into a specific cell of the table.
Here's what I've got so far:
<?php
$conn=#mysql_connect('host', 'username', 'password', 'asteriskcdrdb.cdr');
echo ('total calls ROPCW: ');
$result=mysql_query('select count(*) from asteriskcdrdb.cdr where calldate like "2016-04-11%" and dst="020" and disposition="ANSWERED" and duration > "10" ');
echo mysql_result($result, 0);
mysql_close($conn);
?>
This code will post on my page the count of total calls made on 4.11.2016 like this:
total calls ROPCW: 369
My objective is to create a table like this:
So the result of that query I mentioned above would go on the ROPCW->Total cell (where is 305) on the left side, on the right side are the monthly reports so far.
You can work out one big query or use a view to gather the data you need from a single source. Other suggestion would be, looping through all your branches and gather all the data you need, to build an associative array indexed similar to this:
$records[branch] = [date => [total => x, lost => y], mtd => [total => X, lost => Y]];
Then just do a:
foreach ($records as $branch => $record)
{
echo string to build table row
}
I suggest use mysql_fetch_object or mysql_fetch_assoc functions instead of mysql_result. Basically because those functions fetch an entire row instead of one single cell value. For your example query works fine because your aggregate function returns only one cell and row. But for your desired output won't work.
Keep in mind that you can inject HTML code within PHP and vice versa. Just do something like:
The idea would be run a select * from yourTable;
Then,
$result = mysql_query($sql);
echo "<table>\n";
echo "<tr><th>Branch</th></tr>\n";
while ($callRecord = mysql_fetch_object($result)) {
echo "<tr><td>{$callRecord->branch}</td></tr>\n";
}
echo "</tr>\n";
echo "</table>\n";
That should output a list of all tour branches. this is a guideline.
Hope this helps!!
You can go to www.php.net and choose between mysql_fetch functions which one will work better for you.
I have an external database that I am trying to access from within a Drupal page, I have successfully queried the database and output data to the page using fetchAssoc(), however this only returns the first row in the database. I would like to return all rows into an array for processing, so I'm attempting to use fetchAllAssoc(), this however results in an exception. The database has the following SQL fields:
id, model, manufacturer, url, date_modified
My test code is as follows:
<?php
db_set_active('product_db');
$query = db_select('product', 'p')->fields('p');
$sqlresults = $query->execute()->fetchAllAssoc('id');
foreach($sqlresults as $sqlresult)
{
printf($sqlresult);
}
db_set_active();
?>
I'm thinking that it is the key field 'id' that I am specifying with fetchAllAssoc() that is the problem, as fetchAssoc() prints values correctly. All documentation I have found seems to say that you pass a database field as the key but I have also passed a numeric value with no success.
Many thanks in advance for any advice, I'm sure I'm just missing something stupid.
I think it should work in this way, but within the foreach you want to print the $sqlresult variable as a string, but it is an object (it causes the error).
printf function needs a string as the first parameter, see:
http://php.net/manual/en/function.printf.php
Use for instance var_dump instead:
var_dump($sqlresult);
Is there any way to print the resource_id without mysql_fetch_array.I dont want to loop through result.I want print only the first row at top.I know mysql has been depreciated.This is for old project.
You can make use of arrays in your case
$all_rows = array();
.
. // your query
.
while($dbrow = mysql_fetch_array($query))
{
$all_rows[] = $dbrow;
}
$first_row_array = $all_rows[0]; // first row will be stored here
/*
uncomment the below line if you do not want to use the
first row again while looping through the remaining
rows
*/
/* unset($all_rows[0]); */
foreach($first_row_array as $first_row)
{
// do something with first row data
}
foreach($all_rows as $dbrow)
{
// loop through all the rows returned including the first row
}
A resource in itself is a pretty meaningless type. It only means something to specific functions, like mysql_*. When querying the database, there are certain resources allocated on the MySQL server which hold your requested result; PHP doesn't really have access to those results yet. To give you a handle on those resources on the MySQL server, you get a resource type variable. It's basically just your ticket, saying "if you ever want to access that data waiting for you on the MySQL server, use this number."
So, if you want to output the data from the MySQL server, you will have to fetch it from there, e.g. with mysql_fetch_assoc. That then returns the data to you which you can print.
If you just want the first result, just call that function once.