I have a 2 field database (daynumber & datavalue), the data of which I am retrieving with php then creating and passing variables into jquery for use with a graph.
I am not doing this as an array because I need to apply a formula to the datavalue field. The formula can be altered by the user.
In jquery, I need to be able to do this:
cday_1 = <?php echo $day_1?>;
cday_2 = <?php echo $day_2?>;
tday_1 = (<?php echo $day_1 ?> * formula1 / formula2;
tday_2 = (<?php echo $day_2 ?> * formula1 / formula2;
The cday series and the tday series will be plotted separately on the graph.
My problem is that I could manually name each var in php, ie:
$day_1=mysql_result($result,$i,"datavalue");
but I have 30 rows and I'd prefer to do it with a loop. So far, I've got this far:
$i=0;
while ($i < $num) {
$datavalue=mysql_result($result,$i,"datavalue");
echo "\$day_";
echo $i;
echo " = ";
echo $datavalue;
echo "<br>";
$i++;
}
So there are a couple of problems I'm having with this.
The first problem is that while everything is echoing, I'm not sure how to actually create variables like this(!).
The second problem is that there are only 30 rows in the db, but 34 are actually outputting and I can't work out why.
I'm self-taught, so apologies for clumsy coding and/or stupid questions.
You could just store them in a PHP-side array:
$days = array(
'cday' => 'the cday value',
'dday' => 'the dday value',
etc...
);
and then via json_encode() translate them to a Javascript array/object automatically. This object could be sent to your page as an AJAX response, or even embedded into the page directly:
<script type="text/javascript">
var days = <?php echo json_encode($days) ?>;
</script>
after which you just access the values as you would any other array in JS.
Have ended up doing this:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
I have a feeling this was a basic issue and I just didn't explain myself properly. I am unable to use an array as I needed to fiddle with formulas so this solution worked fine.
Related
Context:
I'm trying to make an automatically generated list that has a different amount of items on each page. Each item needs a name and a link, based on its place on the list. Here's an example with two items for the problematic part:
PHP variables:
$item_link_1 = "link1";
$item_name_1 = "first item";
$item_link_2 = "link2";
$item_name_2 = "second item";
jQuery:
$("#items").each(function(i) {
$(this).find("a").attr("href", "<?php echo $item_link_"+ ++i +";?>");
});
$("#items").each(function(i) {
$(this).find("a").text("<?php echo $item_name_"+ ++i +";?>");
});
HTML output:
<div id="items">
first item
second item
</div>
Problem:
Obviously, $item_name_"+ ++i +"; will never work. I need a way to add the number generated by jQuery to the end of the variable and echo this new variable.
So, if it's the 4th item, the variable will be $item_name_4. The value of this variable (set manually) will be displayed by jQuery with the text() function.
At least that's my idea for how to automate the process. If there's a way to do this, please tell me. If you know a better way, please tell me.
The problem your having is the difference between server-side processing and client-side processing.
An easy way to think about this is that PHP is handled before the HTML is even put on the screen replacing all the PHP parts with their variable contents. meaning that adding that php text with a client-side language like javascript won't be able to execute the php code and achieving the results you're after.
Luckily your example can be done explicitly in php:
<?php
$links = array(
array('link' => "Link1", 'name' => "first item"),
array('link' => "Link2", 'name' => "second item")
);
?>
<div id="items">
<?php for($i = 0; $i < count($links); $i++){ ?>
<?php echo $links[$i]['name']; ?>
<?php } ?>
</div>
So I'm setting up a little page for myself to see my online transactions in dogecoin.
I have the RPC server/client connection established and working correctly.
The listtransactions method provides me with the transaction history as an array, which breaks down into its elements. I embed these in a table.
That all works correctly. what I WANT is to take the transaction ID and make it linkable to the dogecoin blockchain record.
Here is the code, and then I will note which lines have the issue:
for($i=count($json)-1; $i>=0; $i--){
echo '<tr>';
echo '<td>'.$json[$i]['address'].'</td>'."\n";
//echo '<td>'.$json[$i]['category'].'</td>'."\n";
echo '<td>'.$json[$i]['amount'].'</td>'."\n";
//echo '<td>'.$json[$i]['confirmations'].'</td>'."\n";
echo '<td>'."<a href='https://dogechain.info/tx/$json[$i]['txid']'>".$json[$i]
['txid'].'</a> </td>'."\n";
echo '</tr>';
}
echo '</table></center>';
?>
The line containing the hyperlink is where it screws up. You can see how it is displaying at http://www.suchco.in/
an example link it gives me is: https://dogechain.info/tx/Array%5B
what it should be is: https://dogechain.info/tx/ fab3b949cb3a71e79fa6b631d5d16aa7268b77dc3626e2fb2e711f1b43adc08d
how can I make this happen?
Put { } around your array variables in a string.
Try:
{$json[$i]['txid']}
Instead of:
$json[$i]['txid']
OR
Do string concatenation
echo '<td>'."<a href='https://dogechain.info/tx/".$json[$i]['txid']."'>"
okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.
I have a map on my site that has plots placed on it using data from my table. The plots are placed with javascript as so...
addPostCode('<?php echo $array[$UID][0]; ?>');
addPostCode('<?php echo $array[$UID][1]; ?>');
addPostCode('<?php echo $array[$UID][2]; ?>');
Somehow I need to see if the variable exists in my table, and then if so, generate an additional line and increment my array number, so based on the above 3 records, the next line would be...
addPostCode('<?php echo $array[$UID][4]; ?>');
Can I ask if this is possible?
You just need to loop through all of the members of the $array[$UID] variable.
<?php
foreach($array[$UID] as $thing) {
$encodedThing = json_encode($thing);
echo "addPostCode($encodedThing);\n"
}
?>
I used json_encode() because it does whatever escaping is necessary to make your data JavaScript-compatible.
If I understand you well, this is what you would do:
addPostCode('<?php $i=0; while (isset( $array[$UID][$i])) { echo $array[$UID][$i]; $i++ ; } ?>');
That would replace all your addPostCode() calls also.
I have a personal message system in my website done simply with php/sql. Actually I am facing the trouble to display them using jquery. The db has as fields: message_id, message_from, message_to, message_topic, message_subject and message_status. The way I am showing the message_topic is repeating eight times the following:
echo '<table><tr><td>';
retrieve_msg_topic($result);
echo '</td></tr>'; //of course I won't make 8 tables!!!
the function called is:
function retrieve_msg_topic($result)
{
if($row = mysql_fetch_assoc($result))
{
echo $row['usernombre'];
$message_topic = stripslashes($row['message_topic']);
echo '<div id="msg'.$row['message_id'].'">';
echo $message_topic;
echo '</div>';
//this will return: <div id="msgN">message topic (title, commonly subject)</div>
}
} //end function retrieve msg topic
So far I have a list on a table with the last eight messages sent to the user. The following row is reserved for pagination (next/prior page) and, after that, another row showing the message I select from the list presented, like we see in Outlook. Here is my headache. My approach is to call another function (8 times) and have all of them hidden until I click on one of the messages, like this:
echo '<tr><td>';
retrieve_msg_content($result);
retrieve_msg_content($result); //repeat 8 times
echo '</td></tr></table>';
the function this time would be something like this:
function retrieve_msg_content($result)
{
if($row = mysql_fetch_assoc($result))
{
echo '<script type="text/javascript">
$(document).ready(function(){
$("#msg'.$row['message_id'].'").click(function(){
$(".msgs").hide(1000);
$("#'.$row['message_id'].'").show(1000);
});
});
</script>';
echo '<div class="msgs" id="'.$row['message_id'].'" style="display: none">'
.$row['message_subject'].
'</div>';
}
/* This function returns:
// <script type="text/javascript">
// $(document).ready(function(){
// $("#msgN").click(function(){
// $(".msgs").hide(1000);
// $("#N").show(1000);
// });
// });
// </script>
// <div class="msgs" id="N" style="display: none">Message subject (body of message)</div>
*/
} //end function retrieve msg content/subject
I could simply explain that the problem is that it doesn't work and it is because I do if($row = mysql_fetch_assoc($result)) twice, so for the second time it doesn't have any more values!
The other approach I had was to call both the message_topic and message_subject in the same function but I end up with a sort of accordion which is not what I want.
I hope I was clear enough.
The easiest way to fix your troubles would be to copy the results of the MySQL query into an array
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
And then use that to build your tables.
edit: What I meant was more along the lines of this:
while($row = mysql_fetch_assoc($result)) {
$yourArray[] = $row;
}
echo '<table>';
foreach($yourArray as $i) {
retrieve_msg_topic($i);
}
echo '<tr><td>';
foreach($yourArray as $i) {
retrieve_msg_content($i);
}
echo '</tr></td></table>';
And then removing everything to do with the SQL query from those functions, like this:
function retrieve_msg_topic($result) {
echo '<tr></td>'$result['usernombre'];
echo '<div id="msg'.$result['message_id'].'">';
echo stripslashes($result['message_topic']);
echo '</div><td></tr>';
}
Right now you're doing some weird key mojo with ret[0] being the topic and $ret[1] being the message, which isn't a good practise. Also, I don't see the declaration of $i anywhere in that code.
The error suggests that the result is empty or the query is malformed. I can't be sure from the code I've seen.
A few other notes: it seems weird that you're using stripslashes() on data that's directly from the DB. Are you sure you're not escaping stuff twice when inserting content into the DB?
Always use loops instead of writing something out x times (like the 8 times you said in your question). Think of a situation where you have to change something about the function call (the name, the parameters, whatever). With loops you have to edit 1 place. Without, you need to edit 8 different places.
BTW, another solution to this problem would be using AJAX to load content into the last cell. If you're curious, I could show you how.
more edits:
For AJAX, build your message list as usual and leave the target td empty. Then, add a jQuery AJAX call:
$('MSG_LIST_ELEMENT').click(function() {
var msgId = $(this).attr('id').replace('msg','');
$.get(AJAX_URL+'?msgID='+msgId,function(data) {
$('TARGET_TD').html(data);
})
});
Replace the capitalized variables with the ones you need. As for the PHP, just echo out the contents of the message with the ID $_GET['msgID'].
However, make sure you authenticate the user before echoing out any messages, so that someone else can't read someone's messages by switching the id number. Not sure how authentication works on your site, but this can be done by using session variables.