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.
Related
Im building an application to track certain information about the clients we deal with like name/date/hrs worked/phone number etc. This information is stored in a db. Because we have different departments like SEO/WEB/Sales etc, and different people within these teams, the app provides different ways to filter the information depending on the filter button pressed.
When someone presses a "filter button", in this example, lets say they pressed the "view by department" button, it takes them to actual hardcoded pages.
As an example:
viewSeoAccs.php
viewWebAccs.php
ViewSalesAccs.php
And in these pages i have queries which pull the information based on the filter pressed but the html is the same. Now here comes the problem.
I have many different pages(based on filters) and every time there is an edit to be made to the html, i have to go into EVERY PHP page to implement the changes.
What i want to do is create a function that spits out the html for me. I have gotten about half way and i know the problem, just cant seem to find a solution.
Here is some code.
In my functions.php file, i have a function called "htmlBlockTEST" that has this code.
EXAMPLE: (code chopped for easy reading)
<?php
function htmlBlockTEST(){
echo '' ?>
<h2 class="accName fl"><?php echo $row['company_name']; ?></h2>
<div class="<?php echo $row['acc_risk']; ?>"> Risk Level. </div>
//ALOT MORE CODE goes here lol.
<?php
}
?>
This is in the header and bought in via "include_once('functions.php').
Under this, i have specific variables that pull in the queried data. (example below)
$pullAllAccounts = "SELECT * FROM tlm_accounts ORDER BY company_name ASC;";
$pullAllAccountsDoIt = mysqli_query($c2d, $pullAllAccounts) or die ("could not pull WEB team data" . mysqli_error($c2d));
?>
now i loop through the db and display the information like so:
<?php
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$compName = $row['company_name'];
?>
<?php htmlBlockTEST(); ?>
<?php
}
?>
In this code directly above, where the function call "htmlBlockTEST" is, is where the problem is. Since The variables which hold the queries are outside the function, I'm assuming that they aren't being passed into the function. I dont want to put them inside the function because the HTML is the same throughout all the pages, but not ALL data.
I need the variables that hold for example $row['company_name'] to be also available inside the function so that it doesn't throw "undefined variable" errors.
How can i make this happen? What is the best way to get these variables in the while loop(or otherwise) to be available inside the function???
PS, ive google and found things like $GLOBALS['x'] etc but from what ive read, its not the best way or easiers and overall im confused on how to even use it.
Any help is greatly appreciated.
Thanks in advanced.
Option 1:
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
htmlBlockTEST($row);
}
Option 2:
global $row;
while($row = mysqli_fetch_array($pullAllAccountsDoIt)){
$compName = $row['company_name'];
htmlBlockTEST();
}
//and in your htmlBlockTEST() function just right this:
function htmlBlockTEST(){
global $row; ?>
<h2 class="accName fl"><?php echo $row['company_name']; ?></h2>
<div class="<?php echo $row['acc_risk']; ?>"> Risk Level. </div>
<?php
//ALOT MORE CODE goes here lol.
}
?>
You have some more options of course.
What I would like to do is find a way to "hide" the option value listing from the page source if possible.
I have successfully created a page with multiple drop downs (6 now, will be 15+ in total); database queries are working, drop downs are working, posting selections and results are visible in a separate processing page, HOWEVER;
The option values are showing in the page source.
Page Design (for this example)
test.php - contains db connect (will change that to separate include_once later), queries, option values code, and table data.
index.php - contains only an include statement calling test.php.
Running test.php in a browser exposes queries (which I don't want) and loading the index that is including test.php hides queries, but shows options which I prefer not to have.
I have searched everywhere (maybe I am not asking the question properly) and have tried to run the sql in one page and posted the result to another, but I cannot get it to work.
What I wanted to do:
Run MySQL queries in a separate "function" page and then call the output (select name) to another (HTML) page and embed the dropdowns into a cell of a table.
Questions:
Is it possible to hide the option values in the index.php page?
Is this my design flaw and if so, what is a better way?tem
How do I run queries in one page, and then call the output of that query as a drop down into an HTML page?
test.php (Shortened example)
<!--mo-->
<td colspan="2"><div align="right"><font face="Arial, Helvetica, sans-serif">
<?php
$query = "SELECT date_code_mo, date_code_mo_desc FROM tbl_gm_assy_date_code_mo ORDER BY date_code_mo ASC";
echo '<select name="date_mo">';
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['date_code_mo_desc'] . '">' . $row['date_code_mo'] . '</option>';
}
mysqli_free_result($result);
}
echo '</select>';
?>
</font></div></td>
<!--week-->
<td colspan="2"><div align="left"><font face="Arial, Helvetica, sans-serif">
<?php
$query = "SELECT date_code_wk, date_code_wk_desc FROM tbl_gm_assy_date_code_wk ORDER BY date_code_wk ASC";
echo '<select name="date_wk">';
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['date_code_wk_desc'] . '">' . $row['date_code_wk'] . '</option>';
}
mysqli_free_result($result);
}
echo '</select>';
?>
index.php source (table definitions not shown)
<select name="date_mo"><option value="Janurary">01</option><option value="Feburary">02</option><option value="March">03</option><option value="April">04</option><option value="May">05</option><option value="June">06</option><option value="July">07</option><option value="August">08</option><option value="September">09</option><option value="October">10</option><option value="November">11</option><option value="December">12</option></select>
<select name="date_wk"><option value="First">A</option><option value="Second">B</option><option value="Third">C</option><option value="Fourth">D</option><option value="Fifth">E</option></select>
I have used a lot of examples available on here to get this far, and I am sure it is something small that has been missed, regardless, THANKS TO YOU ALL!
I'm not sure if I understand your question..
1)
I don't understand why you are worried about option values in the page source, they are simply a value send to the server. Where they are interpreted and get their meaning. You can change them to anything you want. Only the client side code (where the option tags appear) is visible for the user, the serverside code is not visible for the user. --> the user can see the values of the option tags, but has no idea what you are going to do with them serverside.
2) see 1)
3) when submitting a form, the values are send to the url specified with the action attribute:
<form action="evaluate.php" method="post">
...
</form>
The output of evaluate.php will be send to the client --> this is the next page the user will see. For the syntax to form dropdown menu's check here:
Pre-filling select tags from array
For retrieving the values send, have a look at the:
$_GET['varname'] or $_POST['varname'] arrays. Depending on the method specified in the form tag, the values send are stored here.
Where varname = the name attirbute of the form element. Depending on the type of the formelement it is more or less trivial to extract the values. There are plenty of tutorials arround and very easy to find.
I also recommend having a look at the following topic:
How can I prevent SQL injection in PHP?
You're looking for cascading dropdowns, it's the best way to manage it in your case. This question is already answered here:
How to make a Cascading Drop Down List in PHP using jQuery
It uses a classic example of selecting cities based on a selected country, but you can easily adjust it for yourself, by adding .change() function for all of your dropdowns except the last one and adding a php script that returns the right list.
There's also a plugin for JQuery, if you want to check it out:
jQuery Cascading Dropdown Plugin
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>
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
A bit complicated, but ill do my best to explain my question.
I have a main file, dashboard.html.
Within that I have a jQuery function to load the mysql_query every 15sec to get the 15 or so variables that I need. (This is a financial/sales webapp...the sales agents want near realtime updates of the sales, orders, $earned..etc) which are displayed in a #div with multiple listitems contained within. No issues with this with the approach that every 15sec, query, then entire div is updated all at once. Because of this I have not attached an Jquery effect (namely fadeIn/fadeOut) to it, as then the entire div is constantly fading. Not the visual effect I would like, but as it stands, it works.
My Goal: To be able to do the mysql_query every 15sec. Grab the variables (which Im already doing currently. But now, I would like to be able to update ONLY the ListItem that has changed and attach the fade effect to just that item, not the entire #div as a whole.
What Im trying to avoid is separating out the query to 15 separate querys, as that obviously that is not efficient.
Hopefully that makes some sense to everyone. Code can be provided, but I dont think it will help at this point .. I need to understand what approach I need to go to develop the correct code. Thanks everyone for your anticipated help.
EDIT: Im adding a bit of code to help clarify where I stand:
dashboard.html
var auto_refresh = setInterval(function (){
$('#order_jq').load('stats_count.php')
}, 15000); // refresh every 15 seconds
and then in the body:
<div class="span8">
<div id="order_jq" class="centerContent">
Patiently loading stats ...
</div><!-- End id="ortder_jq -->
</div><!-- End .span8 -->
stats_count.php consists of (stripped down for clarity)
<?php
require "database/connect2.php";
$result = mysql_query( "SELECT .... NORMAL QUERY...NOTHING FANCY HERE")
while ($row = mysql_fetch_array($result))
{$orders = number_format($row['ordercount']);
$annual_order = number_format($row['annual_order']);
}
and lastly contained within stats_count.php I also include the list items:
<ul class="bigBtnIcon">
<li>
<a href="#">
<span class="icon entypo-icon-phone"></span>
<span class="txt">Orders</span>
<span class="notification"><?php echo $orders?></span>
</a>
</li>
<li>
<a href="#">
<span class="icon brocco-icon-mic"></span>
<span class="txt">Auburn</span>
<span class="notification blue"><?php echo $annual_order ?></span>
</a>
</li>
</ul>
-D
If you have multiple divs to be updated, you have to select them with their class ".class" not id "#id"..
To create mysql_query every 15 seconds, you need to make setInterval(function(),15000) where function must make ajax request to some page where to do this query..
I can advice you to use jQuery Ajax for those requests..
Without knowing more details about what format your data is being returned in its difficult to get into specifics but the general approach would be:
store current values into an object,
create a new object with your incoming values
cycle through the properties of the obect comparing incoming values
to existing values
update individual panels (via classes or more specific id's)
turn incoming values object into current values object in
preperation for next sql query
If i understand correctly, this could be done like this :
- all your listitems must have a class attribute let's say "list_items".
- after getting data with Jquery you can do a jquery.each() on the list_items, this way you can check if the value of that list item == the new value if not you update your list item.
I hope this answers a little bit your question.