So, here is the page in discussion, DONATION RESULTS
What I did was I used the SQL DB to populate rows by totals, works great. Now, I want when the name is clicked, or the ammount is clicked, for a dialog to pop up with all the individual donations that person has recieved. To do this, I need to use
$eachone = mysql_query("SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='***'")
where * needs to automatically fill with the data from the name/previous query. So for example, for the sponsor tk, when you click on the link tk, it should run
SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='tk'
It also needs to be nested inside another while loop. This works, outside of the while loop, just as a test. It retrieves all the names, however, not just the ones for that particular sponsor. But, when I put it inside the other while loop, to put the content inside the div, instead of in some random spot on the page, it doesn't work anymore.
while($row=mysql_fetch_array($eachone)) {
echo $row['donor_first'] . ' ' . $row['donor_last']. ' ';
}
here is my entire code, sorry if its long, shouldnt be too bad.
MY CODE (PASTEBIN)
At Line 71, shouldn't you supposed to close </a> before </td>?
I recommend to check HTML generated to see what happened, if PHP isn't coming with error.
Give us more information to provide a better help.
In line 63 you have opening <tr> tag but it have no closing </tr>
Related
self taught at PHP so please spare me if i made any obvious errors,
im trying to dynamically create an accordion and have the corresponding content beneath each accordion header be created from its corresponding table,(if the header is tacos, the information below would come from the tacos_info table) some of the solutions i came up with im not sure about, cheifly passing a variable value as the table name in the mysqli query.
<?php
//initialize list
$res = mysqli_query("SELECT * FROM tables ORDER BY votes DESC");
//build the accordion header and div content in descending order
while($row= mysqli_fetch_assoc($res)){
//create value for SQL table name to build content
$dbname='$row['name']';
//create the accordion headers
$accordioncontent= '<h3>'.$row['name'].'</h3>';
//build the query that will be used to create the accordion content dynamically
$res2 = mysql_query("SELECT * FROM '$dbname' ORDER BY votes DESC");
//while loop to build the div content dynamically
while($row2= mysqli_fetch_assoc($res2)){
//dynamically create the list items i.e the accordion content
$ranks= '<li id="li $row2['id']">
<div class="tut-img">
<img src="<?php echo $row2['img']?>" width="50" height="70" alt="<?php $row['title']?>" />
</div>
<div class="title"><?php $row2['title']?>
</div>
</li>';
}//close content while loop
//create the submit button that submits according to each accordion divs content
$submitbutton='';
//limit submissions to once per IP, per table
$voted=false;
$vcheck= mysqli_query("SELECT 1 FROM sort_votes
WHERE ip='".$_SERVER['REMOTE_ADDR']."'
AND date_submit=CURDATE()
AND Tablename='$dbname' "
);
if(mysqli_num_rows($vcheck)==1)
$voted=true;
//conditional to assign either a submit or edit
if(!$votedIFC){$submitbutton='Enter opinion<span></span>'}
else{$submitbutton='Enter opinion<span></span>'}
//concatonate the div header with the div content
$accordioncontent .= '<div><ul class="sort" id="rank_ul">'$ranks'</ul><div class="button-holder">'$submitbutton'</div></div>';
}//close accordion while loop
//send all this data to the AJAX GET request
echo $accordioncontent;
?>
am i passing these values to the query correctly? is this allowed? if not what are better alternatives? any and all tips, input and knowledge is much appreciated.
First of all, I can see that you are using simple and double quotes sometimes in a strange way. Which IDE are you using for your development? My first recommendation, would be for you to use a proper editor that will automatically check your code syntax.
For example this seems strange (difficult to ready and will surely at one point generate an error):
'<li id="li $row2['id']"> ..... ';
In my opinion, a correct syntax here would be:
"<li id='li ".$row2['id']."'> .... ";
More details here: http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm
Now to answers to your question, you seems to be more focused on the way you are passing the values to the SQL query. If you are looking for best practices, then I'd recommend you to use php PDO. It's a layer between PHP and your database that will among other things, make sure that the you correctly passed values to SQL (reduce risk of SQL injection, problem of quotes, etc ...).
More details about PDO here: http://code.tutsplus.com/tutorials/why-you-should-be-using-phps-pdo-for-database-access--net-12059
My last advises:
Please make efforts in the indentation of your code, it will be easier to read and understand for you and others and it will then avoid obvious errors.
Use correct variable name. For example you are here using $dbname to speak about database tables ...
Good luck.
I have created a jsfiddle for the following problem. I have tried to recreate it but it is hard because the data is being displayed server-side with PHP from a MySQL database.
I have a table and I am trying to pass the clicked <td> content into my modal box. If it doesn't have any, the modal box should appear with the user id but the input boxes are empty.
For some reason, the user id changes fine but the start time and end time inputs don't! Also, when I inspect the element it displays 8 - 5 for all the users? Does anyone have any idea why this is happening?
php code with the click + data params
for($dow = 0; $dow <= 6; $dow++) {
?><td class="js-clickable" data-user_id="<?php echo $user_id; ?>" data-start_time="<?php echo $row['st']; ?>" data-end_time="<?php echo $row['et']; ?>"<?php
if (array_key_exists($dow, $list)) {
foreach ($list[$dow] as $row) {
if ($row['user_id'] == $user_id) {
echo date("H:i", strtotime($row['st'])) . " - " . date("H:i", strtotime($row['et']));
The problem is with your PHP code as the HTML markup shown in the fiddle clearly shows that the data-end_time and data-start_time for Michael is shown as data-end_time="2015-03-27 17:30:00" data-start_time="2015-03-27 08:30:00".
There might be some error in the values fetched from the database. Make sure that you retrieve the values from the database correctly.
The jquery that you have written works perfectly in this case.
This is a PHP issue, because it was written at the PHP.
Now why it happens like that may be at date("H:i", strtotime($row['start_time'])) and I think the expected value($row['start_time'] and $row['end_time']) don't return a expected string to the strtotime function.
Check your code at this block and check how it is returned.
if ($row['user_id'] == $user_id) {
echo date("H:i", strtotime($row['start_time'])) . " - " . date("H:i", strtotime($row['end_time']));
}
I hope I've helped ya.
I've identified the issues with your PHP code that caused the data to be incorrectly populated in the table.
The main issue was to do with bad logic in the section that writes the tags. For example, the $row variable used to write the data attributes was entirely different from the $row variable used to write the contents of the TD. Also, you were writing the data attributes of the first TD tag before even looking for the schedule for that user. I revamped the code in that section so that the full TD tag is written in two areas, either with scheduled data, or without. The code is still pretty messy, but at least now it works. Also, on line 57 of the code in the pastebin you posted had a misplaced quote between the php closing tag (?>). It was: ?"> It should be: ?>"
A couple of smaller observations:
- Bootstrap CSS was linked twice (one local, one remote). Not part of the issue, just an observation.
- The closing tag for the form and the surrounding div were in the wrong order. Close the form before the div.
Here is the working code to correctly populate the data attributes and content of the table:
// Code removed at request of OP.
I am creating a PHP search page that searches a MySQL database and returns results into separate jQuery modals.
Goal: When a user searches a term, the results found for ClassName are displayed from the database via separate links (these links being scripted to open jQuery modals) and once a link is clicked the modal opens displaying the rest of the information related to that ClassName in said database.
What Is Working: The different ClassName(s) are displayed properly as separate links.
What Is Not Working: No matter what ClassName link you click on, once the modal opens, it only displays the information relating to the very first ClassName result in the database.
Any help correcting this error is greatly appreciated.
The only rows in the database I am using for results are: ClassName, ClassInformation, and imagePath.
PHP Select Statement:
<?php
$raw_results = mysql_query(
"SELECT * FROM classes
WHERE (`ClassName` LIKE '%".$query."%') OR
(`ClassInformation` LIKE '%".$query."%')"
) or die(mysql_error());
?>
Link:
echo "<a href=".$results['ClassName']
. " data-reveal-id='myModal'><h2>"
. $results['ClassName']
. "</h2></a>";
Modal:
echo "<div id='myModal' class='reveal-modal'
style='background-image: url(ResultBackground.png);
border: 1px solid black;'><h2>".$results['ClassName']."</h2>
<div id='image'>".$results['imagePath']."</div></br >
<h3>".$results['ClassInformation']."</h3>
<a class='close-reveal-modal'>×</a></div>";
I apologize for the code not formatting correctly I don't really understand how to use the code blocks on this site yet. But thank you for any and all help offered.
A similar question was asked by someone 2 months ago here related question but the way his code was written threw me off completely as I'm new to PHP and only know the messy way I've taught myself from online tutorials. I attempted to format the code similar to the way suggested by the person who answered the linked question but I just keep breaking my code.
$i=0;
while($row=mysql_fetch_array($raw_results)){
echo "<a href=".$results['ClassName']. " data-reveal-id='myModal_".$i."'><h2>".$results['ClassName']. "</h2></a>";
echo "<div id='myModal_".$i."' class='reveal-modal'>......restcode";
$i++;
}
You have to use unique ids fro each link .here you have used same data-reveal-id="myModal" for every link,and every modal div has same id "myModal". So when you click on any link,it checks for first element with id 'myModal' and displays it .
Use different data-reveal-ids for each link and give the same id to the corresponding modal divs
SAME PAGE RESULTS: (xmain.php)
//FORM (working good)
<form name="search" action="xmain.php" method="post">
code,code,code,
// QUERY (working good)
code,code,code,
<input type="submit" name="doSearch" value="doSearch">
//These are last 2 lines of my 15 line query - I have skipped the rest to save space:
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM $tableName $qryWhere LIMIT $start, $limit;";
$result = mysql_query($sql);
// Table query results here.....
OK, although all code is working correctly ( Form is submitting variables, database results are correct, etc, there are 2 nagging problems:
1 - ALL database results are echoed when the page is first loaded. The page is refreshing from top to bottom without a stop in between - I would like for NO RECORDS to be shown at first page arrival.
2. Also, because of the top to bottom nature of this page,my option choices are being reset upon form submission. I would like to maintain selections until the RESET button -
that I have on the page for that purpose is clicked.
I realize that the form by always refreshing upon itself, is causing the above problems.
Any suggestions would be greatly appreciated! - see working sample here:
http://www.symbioticmusicpublishing.com/database3/xmain.php
Only show something when something is actually posted, so surround with if(isset($_POST['doSearch']){.. or something.
echo a value <input .... value="'.(isset($_POST['thisinputname'])?htmlspecialchars($_POST['thisinputname']:'')">
On more elaborate forms a session could be handy, not needed for simpler ones/forms always getting the post though. BTW, I prefer using GETs for listing data, makes it easier to share/link. POSTs for alterations, GETs for retrieving (and a few other methods for real REST).
Echo the retrieved values inside a if statement like Wrikken suggested. Check that your form submission button is actually clicked and only then echo the results.
If you're unfamiliar with the syntax take a look at ternary operator.
http://www.php.net/manual/en/language.operators.comparison.php
Also use GET if you are getting data from database. And POST when you are putting data into database. I guess the reason why goes beyond the naming convention but still it's a nice reminder: GET for getting and POST for posting/putting.
UPDATE
Sorry I didn't think this one through. Put the sql query inside a if statement. Put also the echoing of results inside a if statement.
if (isset[$_POST['doSearch']]){
//make the query
}
if ($sql){
//echo the results
}
Specific questions are at the end of this (very long) pre-amble. Sorry, I tried to make it as short as poss. (took over an hour to write the question).
A .php file uses a (php) function to read rows in a SQL db and dynamically create an HTML table.
For each row, the SQL data is returned via $book['id'], $book['code'], $book['description'], etc.
The $book['code'] is a two-char alpha-numeric ID, eg. B7 or DW
In the HTML for each row is a <td></td> containing an anchor tag with an onclick= event that runs a JQuery script (to show/hide elements for that row).
Suppose a couple or rows were clicked and a couple of elements were hidden by the embedded JQuery script (which is working correctly, by the way)
When the user views a different page and then returns to this one, hidden elements (that were hidden by the JQuery script) are no longer hidden.
I wish to preserve a string of $book['code'] values for each clicked row an d, upon return to the first page, parse that string to reset the hidden elements.
<?php
function render_row_from_mysql() {
$output .= '
...create header row...
foreach ($books as $book)
{
create table row cells 1, 2, 3, 4
after cell 4:
<td>
<a id="addToShelf.php" onclick="
jQuery.ajax(\'./addToShelf.php?id='.$book['id'].'ats'.'\');
jQuery(addToShelfLink'.$book['id'].')[0].style.display = \'none\';
jQuery(rfs'.$book['id'].')[0].style.display = \'block\';
jQuery(mt'.$book['id'].')[0].style.display = \'none\';
jQuery(grn'.$book['id'].')[0].style.display = \'block\';
return false;
">
add to bookshelf
</a>
</td></tr>' ;
}
}
Questions:
Why doesn't the JQuery code above, which works correctly, need closing parentheses?
What is the syntax for creating/updating a var, in the anchor tag, that would preserve the cumulative clicked-row data? I ask because my many attempts all break the code.
Should the var be initialized at the top of the function, before the foreach loop?
I tried using PHP to create/update a cookie by inserting the following code after "return false;" (see below). The below php code does create a cookie when pasted into a separate script for testing.) The php code does not fire. Why?
The answers are:
1) Still not sure, just syntax.
2) As mentioned in Q4, I had been entering code AFTER the "return false;" statement, which is what concludes the onclick event. Therefore, any code placed after "return false;" would not fire as part of the onclick event... and there was nothing else to MAKE it fire.
3) Irrelevant
4a.) The above code is created within a PHP code block -- one cannot create a PHP code block inside JQuery inside HTML that is being created by (i.e. already inside) PHP.
4b.) Further to answer (2), my alert() tests would not fire because they followed the "return false;" statement,
4c.) Any new PHP code must be moved out of the HTML and placed back with the rest of the PHP, such as above the function(render_row_from_mysql){}.
It is now "back to the drawing board" to figure out how to preserve the "clicked items" data between when a user leaves this page and when he returns back to it. At this time, I suspect that will be some kind of a FORM $POST event, but having never done one before I'm not sure what that will look like.
I completely agree with Bjorn comment from 22 minutes ago. You need to remove all that onclick code and add a identifying class to your anchor tags. You sure also make sure that each HTML element has a unique id, it is a W3C validation requirement. If each book's id is unique system wide I would use that, see Example below:
<?php
function render_row_from_mysql() {
$output .= '
foreach ($books as $book)
{
//create table row cells 1, 2, 3, 4
//after cell 4:
<td>
<a id="'.$book['id'].'" class="addToShelf">
add to bookshelf
</a>
</td></tr>' ;
}
}
Add this javascript code to the bottom of your HTML code.
jQuery(document).ready(function($) {
// bind event to all anchor tags with class addToShelf
$('a.addToShelf').click(function() {
var book_id = this.id;
$.ajax('addToShelf.php?id='+book_id, function() {
// execute code after the ajax request is complete...
$('addToShelfLink'+book_id).hide();
$('rfs'+book_id).show();
$('mt'+book_id).hide();
$('grn'+book_id).show();
});
return false;
});
});