I'm very new to PHP, and as a challenge am trying to make a little inventory control script. The idea is to have the amount remaining of each item be defined through a PHP array, and then be imported into a javascript array for dynamic DOM insertion. The amount remaining of each item sits in a .ini file on the server.
This currently works with the below commented OUT code, but obviously I am defining the array values statically within the page:
<?php
//$quantity = fopen("quantity.ini", "w") or die("Its broked");
$quant = file("quantity.ini");
//$quant = array();
//$quant[0] = 13;
//$quant[1] = 90;
echo "var uniforms = [" ;
echo "{" ;
echo "\"item\" : \"Item1\", ";
echo "\"descr\" : \"Blue Hat\", ";
echo "\"size\" : \" 6-12 \", ";
echo "\"colour\" : \"Black/Blue/Green\", ";
echo "\"img\" : \" \", ";
echo "\"quant\" : \"" . $quant[0] . "\" ";
echo "}," ;
echo "{" ;
echo "\"item\" : \"Item2\", ";
echo "\"descr\" : \"Black Hat\", ";
echo "\"size\" : \" Large \", ";
echo "\"colour\" : \"Black\", ";
echo "\"img\" : \" \", ";
echo "\"quant\" : \"" . $quant[1] . "\" ";
echo "}," ;
echo "]" ;
for ($i=0; $i < count($quant); $i++)
{
fwrite($quantity, $quant[$i] . PHP_EOL);
}
fclose($quantity);
?>
I know that I don't need to echo the entire Javascript array, whoops :)
I had thought that each line of the file would be brought into a an array called $quant, as per this post.
The INI file, with the commented code invoked and the file() function removed properly writes to the .ini file as whatever values I modify quant[0] and quant[ 1] too.
Write out Jason using json_encode, JavaScript will read that fine, then you can get rid of most of your code
I realize the OP is new to PHP, etc...
But... the correct answer is: use a database, not a flat file.
it's relatively easy to set up a MySQL or SQLite db
Sorry
Related
I am trying to display a list of friends using PHP and SQL, and my code partially works. However, it is returning the same result on multiple occasions and I would like it not to.
The SQL:
$sql =
"SELECT ubuser.usr_firstname, ubuser.usr_lastname, ubuser.usr_DOB,
ubuser2_1.usr_firstname & \" \" & ubuser2_1.usr_lastname
AS UBFriend, ubFriendsLink.ub_lnkID1, ubFriendsLink.ub_lnkID2, ubuser.usr_ID,
ubuser2_1.usr_ID
FROM ubuser
AS ubuser2_1
INNER JOIN (ubFriendsLink INNER JOIN ubuser ON ubFriendsLink.ub_lnkID1 = ubuser.usr_ID)
ON ubuser2_1.usr_ID = ubFriendsLink.ub_lnkID2
WHERE (((ubFriendsLink.ub_lnkID1) = ".$_SESSION['usr_ID'] ."))
OR (((ubFriendsLink.ub_lnkID2) = ".$_SESSION['usr_ID'] ."))";
The SQL works (or seems to).
The code for displaying the result:
<?php
$nrecs=0;
while (!$FriendsRs->EOF) {
$nrecs++;
?>
<? php
if (.$SESSION['usr_ID'] == ['ub_lnkID1'])
{
echo <p>Name: <?php echo $FriendsRs->Fields['UBFriend']->Value ?><br/ >
<? php
else
echo <p>Name: <?php echo $FriendsRs->Fields['usr_firstname']->Value ?> <?php
echo $FriendsRs->Fields['usr_lastname']->Value ?><br />
<?php $FriendsRs->MoveNext() ?>
<?php } ?>
The result:
Name: Carl Smith
Name: Rob Sanderson
Name: Rob Sanderson
Name: Tony Jackson
The problem seems to be that what I am getting is a list of the names associated with the ub_lnkIDs, where i only want to display the individual names. (FYI, Rob Sanderson is not needed, but it can be returned once).
EDIT:
The desired output is
Name: Carl Smith
Name: Tony Jackson
From what you've described it sounds like you want to remove the duplicates from your list.
I'm not sure what you're trying to do with the session check but your original if/else condition didn't make sense so I changed it to what might be right based on your query.
<?php
$Arrnames = array();
// Produces array containing all the names in the correct format
while (!$FriendsRs->EOF)
{
if ($SESSION['usr_ID'] == $FriendsRs->Fields['ub_lnkID1'])
{
array_push($Arrnames, "<p>Name: ".$FriendsRs->Fields['UBFriend']->Value."<br />");
}
else
{
array_push($Arrnames, "<p>Name: ".$FriendsRs->Fields['usr_firstname']->Value ." ". $FriendsRs->Fields['usr_lastname']->Value . "<br />");
}
$FriendsRs->MoveNext();
}
// Removes the duplicates from the array
$ArrnamesDedupped = array_unique($Arrnames);
// Loops the de-duplicated array and echos the result
foreach ($ArrnamesDedupped as $value)
{
echo $value;
}
?>
if (.$SESSION['usr_ID'] == ['ub_lnkID1'])
My best guess is the single = is causing your if statement to fail
== means is the same as (and can return false) WHEREAS = will always return true! (= is used for setting values.)
Additionally you open <?php tags above the if statement - and then open them again in your <?php echo without closing them?
<? php
if (.$SESSION['usr_ID'] = ['ub_lnkID1'])
{
echo <p>Name: <?php echo //HERE
There are multiple problems.e.g. opening
php tags inside php tags, no closing } for the if clause, html paragraphs (p) opened and not closed etc.
what I think you want to do (not tested):
<?php
$nrecs = 0;
while (!$FriendsRs->EOF) {
$nrecs++;
if ($SESSION['usr_ID'] !='ub_lnkID1') {
echo "<p>Name:" . $FriendsRs->Fields['usr_firstname']->Value . " " . $FriendsRs->Fields['usr_lastname']->Value . "</p>";
}
$FriendsRs->MoveNext();
}
?>
I've took over a PHP app which code is quite a mess so before making any major changes I've decided to rewrite it to MVC (CodeIgniter). As for pure html sections I use $this->load->view(file); technique, but I'm not sure how to cope with something like this:
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
echo "<b>".$kampania[$kamp]['name']."</b><br />";
echo "<div class='szczegolyDiv'><a class=\"pokaz szczegoly\" href=\"?pokaz=".$kampania[$kamp]['idProject']."\">";
echo "SZCZEGÓŁY";
echo "</a></div>";
if (isset($kampania[$kamp]['timestamp'][$iloLeftCustomers-1])) echo "<br />Dane od: <br /><b>".$kampania[$kamp]['timestamp'][$iloLeftCustomers-1]."</b>";
echo "<br />do: <br /><b>".$kampania[$kamp]['timestamp'][0]."</b>";
//echo "<br />".$ilOstatnichRozmow;
polacz();
$querySpr = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$_SESSION['loginid']." AND kampania=".$kampania[$kamp]['idProject'].""));
rozlacz();
if ($querySpr['ile']==0) {
echo "<div id=\"".$kampania[$kamp]['idProject']."\" class=\"tabDodaj\">DODAJ DO OBSERWOWANYCH</div>";
}else{echo "<div class='komunikatMasz'>Masz tę kampanię na liście.</div>";}
echo "</td>";
I'm a beginner in CodeIgniter (and MVC in general), so I don't know all its features and which to choose. Perhaps it's not possible to seperate these 2 technologies completely - so it's more elegant to mainly use html and escape php scripts with <? ?> or to use php and echo html parts?
You can always write html in the template file and insert php in it to loop or echo.
echo "<tr>";
echo "<td class=\"border szczegolyTd\">";
echo "Kamp.: ".$kampania[$kamp]['idProject'];
echo "<br />";
Could be:
<tr>
<td class="border szczegolyTd">
Kamp.: <?php echo $kampania[$kamp]['idProject']; ?>
<br />
Putting code in those PHP tags wil actually fire the call in place. Mind you, to keep the html clean of bussines code make sure you only use echo, foreach, for or if in it.
In CodeIgniter you could render a view file and insert into a "partial" view and just echo it in the main template using TRUE for the 3rd parameter. This only buffers the output instead if immediatly outputting it.
$data['content'] = $this->load->view('ding/templatefile',$vars,TRUE);
if you are really new, please follow this tutorial its nice && informative.
yes it is possible, the best use is short tag + equal sign <strong><?=$variable?></strong> and it echoes whatever is in $variable, whenever you use foreach() use either
foreach($elements as $element) {
$string = "";
$string .= "new line" . $element->id . "<br>";
$string .= "line 2" . $element->name;
echo $string;
}
or just echo lines as you wish
foreach($elements as $element) {
echo "new line" . $element->id . "<br>";
echo "line 2" . $element->name;
}
but remember, before going in to foreach loop, please check if you have valid $variable to go thru. (empty(), isset(), $variable != FALSE...)
note:
if you need condition while echoing basic text use
<strong><?=(condition) ? 'TRUE' : 'FALSE' ?></strong>
example
<strong><?=(isset($variable)) ? $variable : '' ?></strong>
I would advise you go read up on the flow of how a MVC works, but this should point you in the right direction.
In the controller you instantiate the model of the data like:
$this->load->model("lista");
Then,
$data = $this->lista->getCountList($_SESSION['loginid'], $kampania[$kamp]['idProject']);
where in the lista model you have the function:
getCountLista($loginId, $projectId)
which does this part:
return mysql_fetch_assoc(mysql_query("SELECT COUNT(*) AS ile FROM lista WHERE user=".$loginId." AND kampania=".$projectId.""));
Then you pass the returned data to the view
$this->load->view(file, array("listData" => $data));
and in the view:
$listaData[$kamp]['idProject']
It creates an variable in the view foreach item in the array passed in the view.
I commend you to read documentation about MVC.
What I am trying to do is get an echo of the following php call and subtract 14.1% from the displayed number.
The code:
<?php echo $program->current_amount(); ?>
Can I add arithmetic functions to this in order to display the 14.1% deduction?
I think you're looking for a basic math operation in your output that has no effect on a database or anything else, correct?
If so, do something like the following:
<?php
// Set values
$current_amount = 100;
$pcnt_off = 14.1;
// Do the math
$out = $current_amount - ($pcnt_off/100) * $current_amount;
// Output
echo $out . " is " . $pcnt_off . "% off of " . $current_amount;
?>
http://codepad.org/RqF8cuvN
More specifically to your case:
<?php echo $program->current_amount() - 0.141 * $program->current_amount(); ?>
You can perform expressions inside an echo statement, yes; just wrap it in a (), so:
<?php echo ($program->current_amount() - .141); ?>
It may not even be necessary to use (). Incidentally, if your environment supports short tags, you can simply do:
<?= $program->current_amount() - .141 ?>
Keep in mind, though, that that code won't actually remove 14.1% from your number--you would want to multiply by .859.
I have a php code where I am generating javascript using php
function FunJavaScriptRedirection($url)
{
echo "<script>";
echo "var x = ";
echo $url';';
echo "window.open(x)";
echo "</script>";
}
My problem is I want semicolon after storing value to variable x .I dont know how to do that I am getting javascript error please help me out .
Even when you get the concatenation right, your code will still not do what you want as you are outputting "x" I stead of the value of the variable.
So after fixing the concatenation
echo $url . ';';
You need to change the following line:
echo 'window.open(' . x . ');';
And I suspect you should declare the language used inside the script tag...
Change
echo $url';';
to
echo $url . ';';
See Contactenation.
You are missing a point between $url and ';'.
I am using NVU for web development and I encountered a problem that I have searched to fix for quite some time.
<?php
$imagesDir = 'images/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
foreach($images as $key=>$value)
{
echo "<img src='"$value"'>" ;
}
?>
I should get an output of all the images in the "images/" folder, but my output looks like this
" ; } ?>
it only prints what comes after it and none of what I actually want it to print.
What should I do?
Thanks in advance
Probably because you're missing the periods..
echo "<img src='".$value."'>" ;
You can also put in variables within double quotation marks in PHP without the need to concatenate the string.
echo "<img src='$value'>";
You forgot to add the concatenation operator
echo "<img src='" . $value . "'>" ;
you're mising the periods:
echo "<img src='".$value."'>" ;
Also it is worth always checking the error log, take a look at the PHP error log (or if not filtered, the server error log).