Changing data depending on mysql - php

I am getting data from a MySql database, although I don't know if there could be 1 or more hits from the query.
So, i am echoing something from the database, for example like this:
$code = "
<div style='position:absolute; top:100px'>
'$data'
</div>";
echo $code;
Now, since it is absolute; it is overlapping.
How could I change the 'top:' attribute if there are more results?(For every hit from the database, 'top:' would increment by some amount)

$top = 100; // top default value
$query = mysqli_query($link, 'SQL query is going to be here');
while (null !== ($data = mysqli_fetch_assoc($query)))
{
$code = "
<div style='position:absolute; top:".$top."px'>
".$data."
</div>";
echo $code;
$top += 20; // increment top
}

Related

Concatenation & conditions in php

I'm learning PHP and i'm trying to show an " €" when and only when $autocollant_total_ht_custom isset.
This is what i wrote :
$euro = " €";
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else echo " ";
However my " €" is always showing even when $autocollant_total_ht_custom is not set.
I spent 75 minutes on it, trying and failing again and again despite researching.
I also tried with !is_null, !is_empty with the same result.
I'm fairly certain that my logic isn't wrong but the way to do it is.
Anyone to the rescue?
Have a nice Saturday everyone !
Mike.
Edit 1:
A little visual aid image
My goal was to only show the content of a cell if there was indeed something in it. By default i could see 0 in the empty cells.
if (!$autocollant_total_ht_lot10) {
$autocollant_total_ht_lot10 = " ";
} else echo "error ";
if (!$autocollant_total_ht_lot20) {
$autocollant_total_ht_lot20 = " ";
} else echo " ";
if (!$autocollant_total_ht_lot50) {
$autocollant_total_ht_lot50 = " ";
} else echo " ";
if (!$autocollant_total_ht_custom) {
$autocollant_total_ht_custom = " ";
} else echo " ";
I know my code must look primitive but it works and i don't see it making a conflict with what we are trying to achieve in the initial question.
Then, as asked, this is what i'm writing in the table row and table data :
<tr>
<td class=table_align_left>A partir de 100</td>
<td><?php echo $autocollant_prix ?></td>
<td><?php echo $autocollant_custom?></td>
<td><?php echo $autocollant_total_ht_custom?> </td>
</tr>
So in short, i'm trying to not show anything if there's no value to be shown (which is currently working) and then adding a " €" after the variable is there's something to be shown.
Edit 2 :
My primitive code : my_code
Edit 3 :
The $autocollant_total_ht_custom is already conditioned to be shown earlier in this statement :
} elseif($autocollant_quantité >= 90 && $autocollant_quantité <= 99){
$autocollant_quantité_lot50 = 2;
} elseif($autocollant_quantité >= 100 && $autocollant_quantité <= 1000){
$autocollant_custom = $autocollant_quantité;
} else echo "entrée invalide";
$autocollant_total_ht_custom = $autocollant_prix * $autocollant_custom;
$autocollant_total_ht_lot10 = $autocollant_prix_lot10 * $autocollant_quantité_lot10;
$autocollant_total_ht_lot20 = $autocollant_prix_lot20 * $autocollant_quantité_lot20;
$autocollant_total_ht_lot50 = $autocollant_prix_lot50 * $autocollant_quantité_lot50;
$pointeuse_total_ht = $pointeuse_prix * $pointeuse_quantité;
$pointeuse_autocollant_offert = $pointeuse_quantité * 10;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
$pointeuse_autocollant_offert_total_ht = $pointeuse_autocollant_offert * $autocollant_prix;
I posted my code if that can help.
Mike.
//$autocollant_total_ht_custom = null;
$autocollant_total_ht_custom = "something that isnt null";
//if you switch the variable assignment above you will see it behaves as expected.
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo $autocollant_total_ht_custom = $autocollant_total_ht_custom . " " .$euro;
}
else
{
//$autocollant_total_ht_custom wouldn't be set at all if we reach this point, this is why im un-sure what your requirements are. Nothing would be echoed.
echo $autocollant_total_ht_custom;
}
Something like this maybe? It's hard to understand your exact requirements.
IsSet checks if a variable is set to something if its not null then it passes the test, and if you're manipulating strings at this variable then it will never be null, meaning the euro sign will always show up.
If the variable IS null then you fail the conditional test, hit else and echo nothing a null string.
If you can update your answer with what you would expect "$autocollant_total_ht_custom" to be set to, I can help better.
EDIT:
Seems to me you can simplify what you what, basically we are only concerned with echoing a string at all if there is something set, otherwise there's no point doing anything, so your checks could be as simple as
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
if (isset($autocollant_total_ht_custom))
{
echo 'ht custom';
echo TDFromString($autocollant_total_ht_custom, $euro);
}
//notice this doesnt output anything because it isnt set
if (isset($autocollant_total_ht_lot10, $euro))
{
echo 'lot 10';
echo TDFromString($autocollant_total_ht_lot10, $euro);
}
//notice this does because the string, while empty is something that isnt null
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//lets set it to null and see what happens
$autocollant_total_ht_lot11 = null;
if (isset($autocollant_total_ht_lot11))
{
echo 'lot 11 AGAIN';
echo TDFromString($autocollant_total_ht_lot11, $euro);
}
//it doesnt get printed!
//create a function that takes the string in question,
//and for the sake of your use case also the currency to output,
//that way you could change 'euro' to 'currency'
//and have the sign change based on what the value of the $currency
//string is, eg $currency = "£"
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Live example : https://3v4l.org/r5pKt
A more explicit example : https://3v4l.org/JtnoF
I added an extra echo to indicate (and newlines) which variable is being printed out you dont need it of course!
I'll just note the function name is a good example of a bad function name, as it not only returns a td around the string but also inserts the currency, you may want to name it a little better :)
EDIT EDIT:
A final edit outside the scope of your question, you should look into keeping your data in arrays and working on them instead.
Using the previous example we can reduce the code to just this !
$autocollant_total_ht_lot10 = null;
$autocollant_total_ht_lot11 = "";
$autocollant_total_ht_lot12 = "2,0000000";
$autocollant_total_ht_custom = "1,000";
$euro = "€";
//create an array, and stick all our strings in it, from now, if we need to do something to one of the strings(or all!), we do it through the array
$arrayofLots = array($autocollant_total_ht_lot10, $autocollant_total_ht_lot11, $autocollant_total_ht_lot12, $autocollant_total_ht_custom);
//go over each array 'entry' so the first time is '$autocollant_total_ht_lot10', then '$autocollant_total_ht_lot11' etc
foreach ($arrayofLots as $lot)
{
//and we've been over this bit :)
//$lot is a variable we set so we have something to refer to for the individual array entry we are on, we could just as easily name it anything else
if (isset($lot))
{
echo TDFromString($lot, $euro);
}
}
function TDFromString($string, $currency)
{
return '<td>' . $string . ' ' .$currency . '</td>';
}
Good day. It looks like you are missing the end brace
if (isset($autocollant_total_ht_custom)) {
$autocollant_total_ht_custom = $autocollant_total_ht_custom . $euro;
} else {
echo " ";
}

PHP echo 5000 records and Unset

I would like to echo records from a large data set of 300000.
echo first 5000 records than unset($data) and iterate until end of records in the mysql table.
Something like this,
1)
for ($i=0; $i < 5; $i++) {
$data = openssl_random_pseudo_bytes(1000000);
echo "peak_memory_usage = ” . memory_get_peak_usage(true) . “\n”;
doSomething($data);
//unset($data);
}
echo “for loop completed, memory now at ” . memory_get_usage(true) . “\n”;
function doSomething($data) {
echo “size:” . strlen($data) . “\n”;
}
or something like this?
2)
nRows = $pdo->query('select count(*) from employees')->fetchColumn();
$users = new ArrayIterator(range(1, nRows)); // nRows are 3000000 test records
foreach(new LimitIterator($users, 0, 50000) as $u) {
echo $u, "\n";
}
OR
3) #Sameer would you like to add your suggestion to the query below, I might be doing something wrong adding usleep-my coding flaws, which causes the issue of timeout when usleep is added.
$data = $DB->query("SELECT * FROM user_details")->fetchAll();
foreach ($data as $row) {
echo $row['username']." -- ID :" .$row['user_id']. " -- FirstName :" .$row['first_name']. "<br />\n";
}
The third 3) options works fine 50,000 records not much of load on RAM but CPU, is there a way to optimize this to reduce the load on CPU, imagine if 30 people run the same query it will maxed out the CPU? and if i add usleep(10) - it echos the records but with an error at the end saying timeout.
Any suggestions are highly appreciated please.
many thanks for reading my post.
Modified the original post as the objective is the same to reduce load on
the server.. If you like my lengthy post, please vote guys, I am way
behind and I would like to be a contributor in future.
I stumble across an amazing solution by (Dm4Web) data load - amazing solution - but need HTML tables/append o be added and append the results.
Splitting an AJAX call which returns 5000 rows into multiple AJAX calls with 100 rows
Getting error on line 49 Uncaught SyntaxError: Unexpected identifie, when tried to run the script below:
<!DOCTYPE html>
<html>
<head>
<title>SQL Batch List AJAX and jQuery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<div id="mainform">
<h2>Fetch REcords 5000 at a time</h2>
<div id="listData">
<div>
<input id="load" name="load" type="button" value ="Load Data">
<input id="cancel" name="cancel" type="button" value ="Cancel">
</div>
</div>
</div>
</body>
<script>
// counter that allows you to get a new set of rows
var step = 0;
// set variable if you want to restrict the number of rows will be loaded
var maxStep = 0;//
// how many rows should be returned
var count = 5000;
// if the cancel button is pressed
var cancel = false;
$(function() {
$('#load').click(function(){
getData();
})
$('#cancel').click(function(){
cancel = true;
})
});
function getData()
{
step++;
//If cancel variable is set to true stop new calls
if(cancel == true) return;
// checks if the variable is set and limits how many rows to be fetched
if(maxStep >0 $$ step >= maxStep)
$.post('ajax.php'
,{
'step':step,
'count':count,
}
,function(data, textStatus, jqXHR){
if(textStatus == "success")
alert("Data: " + data);
/* foreach (data as $row) {
echo $row['username']." -- ID :" .$row['user_id']. " -- FirstName :" .$row['first_name']. "<br />\n";
} */
if(textStatus == "error")
alert("Error: " + jqXHR.status + ": " + jqXHR.statusText);
// when it finishes processing the data, call back function
getData();
}
,'json'
)
}
</script>
</html>
==== ajax.php =====
step = 0;
if(isset($_POST['step'])) $step = (int)$_POST['step'];
$count = 0;
if(isset($_POST['count'])) $count = (int)$_POST['count'];
if($step>0 and $count>0)
{
$offset = ($step-1) * $count;
$limit = $offset.','.$count;
// --------------
// your code here
// --------------
$data = $DB->query("SELECT * FROM user_details LIMIT .$limit")->fetchAll();
$result = mysql_query($sql);
$arr_result = array();
foreach ($data as $row) {
$arr_result[] = $row;
}
$arr_result_enc = json_encode($arr_result);
echo $arr_result_enc;
// echo rows
//echo json_encode($rows);
}
Method 4)
$query = "SELECT COUNT(*) as num FROM employees";
//$select_run = mysqli_query($conn, $select);
$result = mysqli_query($conn, $query) or die(mysql_error());
$row = mysqli_fetch_array($result);
$itemcount = $row['num']; // Roughly 300,000 total items
$batches = $itemcount / 2000; // Number of while-loop calls - around 120.
for ($i = 0; $i <= $batches; $i++) {
$offset = $i * 2000; // MySQL Limit offset number
$query = "SELECT first_name,last_name FROM employees LIMIT 2500, $offset ";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
while ($row = mysqli_fetch_array($result)) {
echo $row['first_name'];
}
echo "<BR>";
echo "Run Number: ".$i."<br />";
echo "<BR>";
}
$data is already getting overwritten, so that's not the problem here.
Heavy loops create constant tension on the server, which increases the load.
You can add sleep of few microseconds to allow server free up resources and some breathing time, which will lower the server load. Use usleep and set optimal microseconds.
for ($i=0; $i < 5; $i++) {
usleep(100);
$data = openssl_random_pseudo_bytes(1000000);
}
Ideas to fix your third attempt:
Select the columns you need instead of selecting *.
Cache the result so only need to run it once for each person that loads the page.
Add a LIMIT (paginate) so you only select the first 100 or 1000 rows instead of 50,000. This will also stop the browser from exploding when you load 50k rows at the same time.

Insert iteration data into database

i'm using codeigniter.I want to insert data in every iteration to database.
controller
$fee=500;
$trans_fee=300;
$ins_arr=array(2,3);
$ins_array_count=count($ins_arr) ;
if(!in_array('1', $ins_arr))
{
for($i=0;$i<$ins_array_count;$i++)
{
$ins.'_'.$ins_arr[$i]= ($fee+$trans_fee);
$ins_sum+= $ins_.$ins_arr[$i];
}
}
i want to get the data inside this variable like( $ins_2 and $ins_3) and insert the value of $ins_2 and $ins_3 into db
I got value of $ins_sum correctly
Anyone please answer me
Wrap them in {}:
Using ${} is a way to create dynamic variables, simple example:
${'a' . 'b'} = 'hello there';
echo $ab; // hello there
So,
$fee = 500;
$trans_fee = 300;
$ins_arr = array(2,3);
$ins_array_count=count($ins_arr) ;
$ins_sum = 0;
if(!in_array('1', $ins_arr))
{
for($i=0;$i<$ins_array_count;$i++)
{
//$ins_.$ins_arr[$i] = ($fee+$trans_fee);
${"ins_" . $ins_arr[$i]} = ($fee+$trans_fee);
$ins_sum += ${"ins_" . $ins_arr[$i]};
}
}
echo $ins_2; //result of ins_2 = 800
echo "<br />";
echo $ins_3; //result of ins_3 = 800
echo "<br />";
echo $ins_sum; // total ins sum = 1600

How to go to an end of recordset using php?

Here is the code:
<?php
require'connection.php';
$cons = mysql_query( 'SELECT Subject FROM tblsubject' );
$total_rows = mysql_num_rows($cons);
$counter = 0;
$fields="";
while($row = mysql_fetch_array($cons)) {
if(++$counter == $total_rows) {
$fields .= $row['Subject']. ': { <br/> title: \''.$row['Subject'].'\',<br/> width: \'20% \' <br/>}<br/>';
}
else {
$fields = $row['Subject'].': { <br/> title: \''.$row["Subject"].'\',<br/> width: \'20% \' <br/>},<br/>';
}
}
echo $fields;
?>
The code stated above should produce an output like this below:
General: {
title:'General',
width: '20%',
},
Math: {
title:'Math',
width: '20%',
}
But if the query reaches its last row, the "," should be omitted after the last "}".
I'm getting it right but when I echo it outside the while loop, only the two last row on the database are echoed.
Can someone help me with this? Please tell me where I am going wrong. Thank you very much :D
I need to echo all the data in the table not just the final two.
Don't even bother with a complicated state checker. Just build an array and then implode it. Automatic "proper" number of commas.
while($row = mysql_fetch_array()) {
$array[]= $row['data_you_want'];
}
echo implode(',', $array);
You could try something like this:
$print = '';
while($row = mysql_fetch_array($cons)) {
$row_subject_array[] = $row['Subject'];
}
for($i = 0; $i < count($row_subject_array); $i++) {
$print .= $row_subject_array[$i]. ': { <br/> title: \''.$row_subject_array[$i].'\',<br/> width: \'20% \' <br/>},';
}
$print = rtrim($print, ',');
echo "<br />";
Also a little suggestion: You should stop of use mysql_x() functions. These functions are deprecated, instead of it you can use mysqli_x() function or PDO.
Why shouldn't I use mysql_* functions in PHP?
Hello and Welcome to Stack Overflow!
First of all you should avoid using the mysql class and use mysqli as mysql has been deprecated.
Now for your question, If your MySQL table has an ID column with Auto Increment enabled then you can do this:
SELECT id FROM table ORDER BY id DESC LIMIT 1
However if you want to achieve the same result then I would format my code in the following way:
$cons = mysql_query( 'SELECT Subject FROM tblsubject' );
$fieldsArray = array();
while($row = mysql_fetch_array($cons)) {
array_push($fields_array,$row['Subject']. ': { <br/> title: \''.$row['Subject'].'\',<br/> width: \'20% \' <br/>},<br/>');
}
array_pop($fieldsArray);
array_push($fieldsArray,$row['Subject']. ': { <br/> title: \''.$row['Subject'].'\',<br/> width: \'20% \' <br/>}<br/>');
foreach($fieldsArray as $value) {
echo $value;
}
tada!
i always do:
$var = substr($var,0,-1);
echo $var; //or whatever

Can I show, hide and toggle results in PHP echo?

Basically by clicking the "comment" link the last result of the query should show and by clicking again it should be hidden. I have tried Rocket's code as well but I get an error message in the bottom of the browser and when I click "comments" it just takes me to the top of the page. I would apprieciate some advice on this
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
This is a loop, echoing the same thing over and over, thus making all the divs have the same ID, something2.
IDs need to be unique, you gonna have to make unique IDs for each div.
Something like: <div id='something$i' style='display: none;'> (remembering to increment $i).
Also, you're gonna to escape the quotes in your onclick attribute.
<a href='#' onclick=\"toggle_visibility('something$i');\">
The code should look something like this:
$i = 1; // ID Counter
while($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'>$row[comment]</div>";
$i++; // Increment counter
}
Escape the quotes :
$blah = "onclick='toggle_visibility(\"something2\");'>Comments</a>"
There is an easier way to hiding / showing the next sibling ....
try this
<div style="display:none">some hidden content</div>​
function toggle(el,ev) {
ev.preventDefault(); // prevent the link from being followed
el = next(el); // get the next element
if (el.style.display == "none") { // toggle the display
el.style.display = "block";
} else {
el.style.display = "none";
}
}
/*
Credit to John Resig for this function
taken from Pro JavaScript techniques
*/
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
​
Working example
You can throw in a counter into your code as the while loop is executing to dynamically generate unique id's for each comment div. Or, you can pull a unique field out of the query result for the id's, as long as you hook up to it appropriately later if it ends up being used and remain consistent in the rest of the code.
either
$count = count($result);
...
while (...){
$count--;
echo '... id="something'. $count .'" ...'
}
or...
while (...){
echo '... id="something'. $row['ID'] .'" ...'
}

Categories