I'm new at using pChart. I take data from database to construct the graph.
I will have a random number of rows and I would like to do a graph for each row.
(one row -> one graph). Is it possible?
So far I can do the graph but all the rows are in the same graph.
Here is my code:
<?php
include("pChart/class/pData.class.php");
include("pChart/class/pDraw.class.php");
include("pChart/class/pImage.class.php");
include("pChart/class/pPie.class.php");
$myData = new pData();
$Requete = "SELECT * FROM `day`";
$Result = mysql_query($Requete, $db);
while($row = mysql_fetch_array($Result)){
$hour = explode(" ", $row["g1"]);
$nb = $row["numb"] * 2;
for($i = 0; $i < $nb; $i++){
if ($i%2 == 1){
$time[$i] = ($hour[$i])/ 60;
$myData->addPoints($time[$i],"year");
}else{
if ($hour[$i] == "00"){
$name[$i] = "On";
}elseif ($hour[$i] == "02"){
$name[$i] = "Off";
}
$myData->addPoints($name[$i],"name");
}
}
}
$myData->setAbscissa("name");
$myData->setSerieDescription("year","Application A");
$myPicture = new pImage(600,300,$myData);
$myPicture->setFontProperties(array("FontName"=>"pChart/fonts/tahoma.ttf","FontSize"=>16));
$PieChart = new pPie($myPicture,$myData);
$PieChart->draw3DPie(340,125,array("DrawLabels"=>TRUE,"Border"=>TRUE));
$myPicture->autoOutput("images/example.png");
?>
If I understand the question, you want a picture for every row? In that case I think that you will have to include the lower part of your code (starting from $myData to $myPicture) in the while loop.
Related
I'm trying to save arrays on a MySQL database with PHP.
The code inserts only the first line, if I have an array of 5 elements it just inserts the first element and the others and 4 don't save them for me.
Can anyone tell me where I'm wrong?
Thanks a lot.
<?php
//getting user values
$day = $_POST['Day'];
$nDay = $_POST['n_Day'];
$fieldOne = $_POST['Field_one'];
$fieldTwo = $_POST['Field_two'];
$timeOne = $_POST['Time_one'];
$timeTwo = $_POST['Time_two'];
$idR = $_POST['id_ristorante'];
$day_array = explode(",",$day);
$nDay_array = explode(",",$nDay);
$timeOne_array = explode(",",$timeOne);
$timeTwo_array = explode(",",$timeTwo);
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
$output=array();
//require database
require_once('db.php');
//checking if email exists
$conn=$dbh->prepare('SELECT id_ristorante FROM Orari WHERE id_ristorante=:idR');
$conn->bindParam(':idR', $idR, PDO::PARAM_STR);
$conn->execute();
//results
if($conn->rowCount() !==0){
$output['isSuccess'] = 0;
$output['message'] = "Orario giĆ inserito";
} else {
for($i=0;$i<$len;$i++){
$day = $day_array[$i];
$nDay = $nDay_array[$i];
$timeOne = $timeOne_array[$i];
$timeTwo = $timeTwo_array[$i];
$conn=$dbh->prepare('INSERT INTO Orari (Day, n_Day, Field_one, Field_two, Time_one, Time_two, id_ristorante) VALUES (?,?,?,?,?,?,?)');
//encrypting the password
$conn->bindParam(1,$day);
$conn->bindParam(2,$nDay);
$conn->bindParam(3,$fieldOne);
$conn->bindParam(4,$fieldTwo);
$conn->bindParam(5,$timeOne);
$conn->bindParam(6,$timeTwo);
$conn->bindParam(7,$idR);
$conn->execute();
if($conn->rowCount() == 0) {
$output['isSuccess'] = 0;
$output['message'] = "Errore, riprova.";
} elseif($conn->rowCount() !==0){
$output['isSuccess'] = 1;
$output['message'] = "Orari salvati!";
}
}
}
echo json_encode($output);
?>
When you trying to do count on multiple array as:
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
The and cause the array to be boolean evaluated so the final assign to $len is 1 and that why the loop is done only once and only the first element is inserted to DB.
If all the array in the same length you should just do count on 1 of them as:
$len = count($day_array)
Better practice will be to do count on each on them and then assign $len with the minimum value
Change this line
$len = count($day_array and $nDay_array and $timeOne_array and $timeTwo_array);
To
$len = count($day_array) + count($nDay_array) + count($timeOne_array) + count($timeTwo_array);
I use mysqli API to query a large table, every 1000 rows, but the memory of my server grows up very fast. The memory is 0, even the swap. I don't know how to fix it.
The table has 4 million rows so I query the table each time by 1000.
Here is my code:
<?php
ini_set('memory_limit','32M');
$config = require_once('config.php');
$attachmentRoot = $config['attachment_root'];
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
echo "\nRename The Dup Files With Suffix: .es201704111728es \n";
$startTime = microtime(true);
/**
*
* Move dup file to $name + .es201704111728es
*/
$suffix = ".es201704111728es";
$fileLinesLimit = 100000;
$listSuffix = 0;
$lines = 0;
/**
* Create File List.
*/
$fileList = '/tmp/Dupfilelist.txt';
$baseListName = $fileList.$listSuffix;
//$fs = fopen($baseListName,'w');
$totalSize = 0;
$start = 0;
$step = 10000;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
while($result->num_rows > 0)
{
while($result->fetch_row())
{
/*$fiepath = $row[1];
$uniqueIdsArray = array_unique(explode(',',$row[2]));if(empty($row[3]))throw new \Exception("\n".'ERROR:'.$row[0]."\n".var_export($row[3],true)."\n");
$uniqueFilesArray = array_unique(explode(',',$row[3]));
$hasFile = array_search($fiepath,$uniqueFilesArray);
if($hasFile !== false)
unset($uniqueFilesArray[$hasFile]);
$num = count($uniqueIdsArray);
$fileNum = count($uniqueFilesArray);
$ids = implode(',',$uniqueIdsArray);
if($num>1 && $fileNum>0){
//echo "\nID: $row[0] . File Need To Rename:".var_export($uniqueFilesArray,true)."\n";
$size = intval($row[4]);
if($lines >= $fileLinesLimit){
$lines = 0;
$listSuffix++;
//$fileList .= $listSuffix;
}
array_map(function($file) use ($attachmentRoot,$suffix,$fiepath,$totalSize,$size,$fileLinesLimit,&$listSuffix,&$lines,$fileList){
//$fs = fopen($fileList.$listSuffix,'a');
if($file === $fiepath)
return -1;
$source = $file;
$target = $source.$suffix;
//rename($source,$target);
//fwrite($fs,$source.','.$target."\n");
//file_put_contents($fileList.$listSuffix, $source.','.$target."\n",FILE_APPEND);
//$totalSize += intval($size);
$lines ++;
//echo memory_get_usage()."\n";
//fclose($fs);
//unset($fs);
//try to write file without amount memory cost
//$ts = fopen('/tmp/tempfile-0412','w');
},$uniqueFilesArray);
//echo "Test Just One Attachment Record.\n";
//echo "Ids:$ids\n";
//exit();
}*/
}
echo memory_get_peak_usage(true)."\n";
if(!$mysqli->ping())
{
echo "Mysql Conncect Failed.Reconnecting.\n";
$mysqli = new mysqli($config['DB_HOST'],$config['DB_USER'],$config['DB_PASSWORD'],$config['DB_NAME']);
$mysqli->set_charset('gbk');
if(!$mysqli)
throw new Exception('DB connnect faild:'.mysqli_connect_errno().mysqli_connect_error());
}
//mysqli_free_result($result);
$result->close();
unset($result);
$start += $step;
$sql = "SELECT id,filepath,ids,duplicatefile,filesize FROM duplicate_attachment WHERE id> $start AND duplicatefile IS NOT NULL LIMIT $step";
$result = $mysqli->query($sql);
}
echo "Dup File Total Size: $totalSize\n";
echo "Script cost time :".(microtime(true)-$startTime)." ms\n";sleep(1000*10);
mysqli_close($mysqli);
exit();
I enable the XDEBUG extension.Sorry for that.
I disable this extension and everything goes well.
I ran into this issue with PHP Version 7.3.26 on Centos 7. I worked around it by using unbuffered query (instead of buffered). In the above example, replace
$result = $mysqli->query($sql)
with
$result = $mysqli->query($sql, MYSQLI_USE_RESULT)
I'm attempting to create a PHP script that will create a random code and check it against a database to see if it exists. I'd like it to check that if it exists then generate another createRandomCode() and check it.
Unsure how to proceed with looping until the number of rows are 0.
function createRandomCode($length='6'){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$code= '';
while ($i++ < $length){
$code = $code. substr($chars, rand() % 33, 1);
}
return $code;
}
$shorturl = createRandomCode();
$q = $db - > query("SELECT * FROM maps WHERE url='".$shorturl.
"'");
if (mysqli_num_rows($q) > 0) {
$arr = json_encode($arr);
echo $arr;
}
Sounds like a good candidate for a do...while loop:
do {
$shorturl = createRandomCode();
$q = $db->query("SELECT * FROM maps WHERE url='".$shorturl."'");
} while(mysqli_num_rows($q) > 0);
function regenerateCode(){
global $connection;
do{
$serial2 = rand(0,7);
$check_code = "SELECT * FROM `voters` WHERE `serial` = '$serial2'";
$run_check_code = mysqli_query($connection,$check_code);
$count = mysqli_num_rows($run_check_code);
} while( $count > 0 );
return $serial2;
}
Looking to display a value from the 1st record's 'post' field which is stored in a MySQL database using PHP. The following div is where the value is to be inserted:
<div id="insert1"><?php echo($r); ?></div>
The PHP (Note using MeekroDB):
<?php
require_once 'meekrodb.2.2.class.php';
DB::$user = 'username';
DB::$password = 'password';
DB::$dbName = 'database';
DB::$host = 'hostname';
// get all entries from database table Microblog;
$results = DB::query("SELECT post FROM MicroBlog");
foreach ($results as $row) {
$id = $row['id'];
// loop through each entry - there's 3
for($i = 0; $i < 3; $i++) {
// if it's the 1st entry (id = 1) then get field 'post'
if ($id == 1) {
$r = $row['post'];
}
}
}
?>
Currently #insert1 is blank. What do I need to change to get it into the div? Please note, I want to keep the for loop, as I'll be adding other if's once I get it running. Thanks.
Probably this part is wrong:
// get all entries from database table Microblog;
$results = DB::query("SELECT post FROM MicroBlog");
should be:
// get all entries from database table Microblog;
$results = DB::query("SELECT * FROM MicroBlog");
You're getting id which i think you're not getting from your query.
$id = $row['id'];
Other option:
Comment out $id.
//$id = $row['id'];
and in the if block below, change $id to $i:
if ($i == 1) {
$r = $row['post'];
}
To add number of records:
$x = 0;
foreach ($results as $row) {
$x++;
$id = $row['id'];
// loop through each entry - there's 3
for($i = 0; $i < 3; $i++) {
// if it's the 1st entry (id = 1) then get field 'post'
if ($id == 1) {
$r = $row['post'];
}
}
}
echo $x;
I have a graph that auto fills based on a few values. The values are the goal (total) the current (where it is at now) and in the total height of the graph. I am trying to pull the goal and current out of the database format it into money and it should fill the graph to the point it needs to be.
I had it working with a URL get which was ?current=584559096&goal=1000000000 and I just used $_GET. For easier maintenance for others around I want to pull it from a database which can be updated a post.
The code I have so far is:
<? php function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.0f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
$goal = $row['goal'];
$current = $row['current'];
$percent = round($current / $goal * 100);
$totalheight = 216;
$ourheight = $totalheight * $percent / 100;
$halfofarrowheight = 12;
$arrowheight = $totalheight-$ourheight-$halfofarrowheight;
if($arrowheight < 0)
$arrowheight = 0;
mysql_close($con);
?>
Here is my query
mysql_select_db("databasename", $con);
$result = mysql_query("select * from `dbname`.`tablename");
This is my error Warning: Division by zero in E:\inetpub\wwwroot\test.website.net\web\includes\globalfoot.php on line 36
Line 36 is the $percent = round($current / $goal * 100);
So, I been fooling with this thing for 4 days now trying to just get the numbers out of the goal column and current column format them to money and have the chart fill. For test sake lets say the goal is 1000000000000 and the current is 5000000000.
$row['goal'] = $goal;
$row['current'] = $current;
Please forgive me if I haven't understood your code, but shouldn't the above be:
$goal=$row['goal'];
$current=$row['current'];
Your code should look like this:
mysql_select_db("databasename", $con);
$result = mysql_query("select * from `dbname`.`tablename");
if (!$result || !($row = mysql_fetch_assoc($result))) {
echo "DB error: ".mysql_error();
exit;
}
$goal = $row['goal'];
$current = $row['current'];
// ...
Always, always double-check your variables when doing division.
$percent = ($goal > 0 || $goal < 0) ? round($current / $goal * 100) : 0;