Adjusting SQL line to include a collection - mysql

I have a function call resource of the day which I have duplicated and changed to be called Editors Picks. The function looks in the DB and grabs a ramdom image based on value and todays date.
Here is the SQL Line:
sql_value(
"select resource value
from resource_data
where resource > 5 and
resource_type_field=$rotd_field and
value like '" . date("Y-m-d") . "%' limit 1;"
,0);
I would like to try and adapt this line to pull in a collection instead, this is the SQL line that pulls in a collection image:
sql_query("select collection.ref,
collection.home_page_publish,
collection.home_page_text,
collection.home_page_image,
resource.thumb_height,
resource.thumb_width
from collection
left outer join resource on collection.home_page_image=resource.ref
where collection.public=1 and
collection.home_page_publish=1"
.$filterClause.
" order by collection.ref desc");
Does anyone know how to adapt the top SQL line to pull in the collection information instead, eg can I change date function to so something else?
This is the 2 pages that power the Code:
home.php
<?php
function HookEditorsPickHomeReplaceslideshow ()
{
include_once dirname(__FILE__)."/../inc/rotd_functions.php";
global $baseurl, $view_title_field;
$rotd=get_editors_pick();
if ($rotd===false) {return false;} # No ROTD, return false to disable hook and display standard slide show.
# Get preview width
$sizes = get_image_sizes($rotd, true);
foreach ($sizes as $size)
{
if ($size["id"]=="pre")
{
$width = $size["width"];
break;
}
}
# Fetch title
$title = sql_value("select value from resource_data where resource='$rotd' and resource_type_field=$view_title_field","");
# Fetch caption
$caption=sql_value("select value from resource_data where resource='$rotd' and resource_type_field=18","");
# Show resource!
$pre=get_resource_path($rotd,false,"pre",false,"jpg");
?>
<div class="HomePicturePanel" style="width: <?php echo $width ?>px; background-color:#f1f1f1; height: 409px;">
<a onClick="return CentralSpaceLoad(this,true);" href="<?php echo $baseurl?>/pages/view.php?ref=<?php echo $rotd ?>"><img class="ImageBorder" style="margin-bottom: 0px; margin-top: 0px; border:#CCC; solid: 0px;" src="<?php echo $pre ?>" /></a>
<br />
<div class="ResourceOfTheDayHead">Our Resource of the day</div>
<div class="ResourceOfTheDayText"><?php echo i18n_get_translated(htmlspecialchars($title)) ?></div>
<div class="ResourceOfTheDayCaption"><?php echo $caption ?></div>
</div>
<?php
return true;
}
?>
And this is: rotd.functions.php
<?php
function get_editors_pick()
{
global $rotd_field;
# Search for today's resource of the day.
$rotd = sql_value("select resource value from resource_data where resource>5 and resource_type_field=$rotd_field and value like '" . date("Y-m-d") . "%' limit 1;",0);
if ($rotd!=0) {return $rotd;} # A resource was found?
# No resource of the day fields are set. Return to default slideshow functionality.
return false;
}
?>

I am not fluent with php, but this pseudo-code may be useful.
string whereClause = "WHERE ";
for each (item in collection)
{
whereClause = whereClause + " " + item;
}
string sqlQuery = "SELECT stuff, otherStuff FROM myTable " + whereClause + " ORDER BY thing2";
The SQL injection can come if the items in the where clause are not sanitized. There are many examples on the web of how to prevent this, but the best way is to use parameters instead of dynamic SQL like I am showing above.

Related

MYSQL How can I make dropdown list?

I created a new table in workbench where I want to put a season of a soccer championship.
I don't want to write down every time the team's names, can you help me pls, how can I make like a dropdown list (or set of values, what are the only options for that column), when I begin to type "Bay..." its automatically offer "Bayern München" as the only option.
I don't know how much will this help, but I have made a dropdown list for something else and I hope my way might give you an idea:
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
if($row[id]==10)
{
echo "<option value=$row[id] selected>$row[name]</option>";
}
else
{
echo "<option value=$row[id]>$row[name]</option>";
}
}
echo "</select>"; // Closing of list box
As the same answer above, but using short-hand ternary operator instead of if-else statement, and don't forget to use ' or " when reference to object string index.
foreach ($dbo->query($sql) as $row) //Array or records stored in $row
{
printf("<option value='%s' %s>%s</option>", $row['id'], $row['id'] == 10 ? 'selected' : '', $row['name']);
}
}
echo "</select>"; // Closing of list box

Way to make row count be 0 if no date match and second,third,etc while loop row counts

<?php
if($result = $db->query("SELECT * FROM table")) {
if($count = $result->num_rows) {
echo '<p class="lead">Number of callbacks for today is: ', $count, '</p>';
while($row = $result->fetch_assoc()) {
if ( $row['field'] == date("Y-m-d") ) {
echo $row['otherfield'], '<br>';
}else{
echo "Nothing", '' , '<br>';
}
}
}
}
?>
I have a simple field date verses server date test used in conjunction with a while loop to bring up any callbacks each day if they are due. My issue is that the row will show a nothing for every row so I'll have twenty(example) rows of the text 'nothing' display. I know I could simply place everything in a function and then use the if/else statement outside of the function to display callbacks or not display callbacks....but is there a way to reset the loop counter to zero if the first if/else test fails? I tried placing the $count = 0; in the second else clause but this did not work.

How to echo specific mysql data in specific places using php?

If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>

Dynamically created checkboxes using ajax from sql result set

I am looking to use ajax to dynamically create checkboxes each time you change your selection from a <select> tag, see the below screenshot for a section of the form that is relevant:
NOTE: The checkboxes under "Queues" should be dynamic.
At the moment, when you change the value for Team it grabs the team name (in this case "Test"), then using ajax (POST) it returns the Manager name for that team.
What I want it to do is look up another table that has a list of the "queues" associated with each team; I am going to add an "onchange" attribute in the tags for the "Manager Name" field.
Below is the code I'm currently using to accomplish the Team => Manager Name dynamic filling:
<script>
window.onload = function() {
getManager($("#team").val());
}
function getManager(team) {
$.ajax({
type: "POST",
url: "getManager.php",
data: {team:team}
}).done(function( manager ) {
$("#manager_name").val(manager);
});
}
</script>
And here is the getManager.php file that it uses:
<?php
require("../../database/db.php");
$mysqli = new db("nab_reporting");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$team=$mysqli->real_escape_string($_POST['team']);
$result = $mysqli->query("SELECT manager_name FROM team WHERE teamname = '".$team."'");
$row = $result->fetch_assoc();
echo $row['manager_name'];
mysqli_close($mysqli);
?>
Keeping in mind that the above works; I now need a way to use the onchange attribute of the Manager Name field that will use ajax (similar to above), passing another php page the value that is currently in the field (in this case Kane Charles) and will return a result set (array or JSON maybe?) containing a list of all queues in the database that match up with that Team name.
Below is the html code for each of the different bits:
TEAM
<select name="team" id="team" required="required" onchange="getManager(this.value)">
<?php
include(__DIR__ . "/../../database/db.php");
$db = new db("nab_reporting");
$result = $db->query("SELECT teamname FROM team");
while ($row = $result->fetch_assoc()) {
echo "
<option value=\"" . $row['teamname'] . "\">" . $row['teamname'] . "</option>
";
}
$db->close();
?>
</select>
MANAGER NAME
<input type="text" name="manager_name" id="manager_name" required="required" onchange="getQueues(this.value)">
QUEUES
<label>
Queues
</label>
<div id="queue_options">
<!-- queues dynamically created here -->
</div>
I need the contents of queue-options to be erased and reset to only the queues associated with the current team; I haven't done a great deal with ajax, hence why I'm posting on here.
This revision should match what you are asking about
PHP
// make an array to hold the queues
$data = Array();
// Fetch the rows of all the queues
$res = $mysqli->query("SELECT * FROM the_queue_table WHERE manager='" . $_GET["manager"] . "'");
// loop through all the rows and push the queues into the data array
while(($row = mysql_fetch_object($res)) !== false)
{
array_push($data, $row->queue);
}
// return the data array as a json object
echo json_encode($data);
JavaScript
// get the page and send the manager name to filter with
$.get("file.php?manager=" + managerName, function(page)
{
// parse the json into an object
var data = $.parseJSON(page);
// remove existing checkboxes
$("#queue_options").children().remove();
// add checkboxes to the div
for (var item in data){
$("#queue_options").append("<input type=\"checkbox\" value=\"" + item + "\" />" + item + "<br />");
}
});

nested while loop mysql_fetch_array

I have a set of nested while loops to compare to mysql queries to each other. Here is the code:
while($row = mysql_fetch_array($resultbat))
{
$drafted = 0;
while($crossedRow = mysql_fetch_array($crossedAnswer))
{
if($row['NAME'] == $crossedRow['name'])
{
$drafted = 1;
}
else
{
$drafted = 0;
}
}
if ($drafted == 1)
{
echo "<tr class='drafted' id='" . $row['NAME'] . "'>";
}
else if($n&1)
{
echo "<tr id='" . $row['NAME'] . "'>";
}else
{
echo "<tr class='alt' id='" . $row['NAME'] . "'>";
}
...}
In the $resultbat is a list of all players, and in the $crossedAnswer is a list of a few players that should be marked. For each player I want to see if they are in the $crossedAnswer list of players. If they are I want to mark the class of that html element to drafted.
Thanks in advance.
I think you'll either need to:
open the cursor on $crossedAnswer for each row from $resultbat (open it at the beginning of each loop through, and close it at the end, which effectively runs that query for each for in resultbat), or
fetch all of the rows from the $crossedAnswer resultset into a structure, and look through that structure for each row from $resultbat, (to avoid running the same query multiple times against the database), or
ensure that both $resultbat and $crossedAnswer are ordered by key value, and do just a single loop; open both cursors, fetch a row from each, and then compare the key values to determine which resultset is "behind", and which one to fetch from (this is more efficient, but is more complicated code to write and test), or
if these resultsets are from the same MySQL server, rewrite this as a single query, and let MySQL do the work of joining the rows together, and process just a single resultset.
Personally, I would opt for the last. I would let MySQL do the join, get a single resultset back, and a single loop.
The query to get the resultset would be of the form:
SELECT b.*
, IF(a.name IS NOT NULL,1,0) AS drafted
FROM (
query_for_$resultbat
) b
LEFT
JOIN (
query_for_$crossedAnswer
) a
ON b.name = a.name
Note that if a matching row is found in a, then the drafted column will return a 1, otherwise, it will return a 0.
The code to handle this resultset, based on the original code could be something like this:
while($row = mysql_fetch_array($result))
{
$class = "";
if($row['drafted'] == 1
{
$class = "class='drafted' ";
}
else if($n&1)
{
$class = "";
}
else
{
$class = "class='alt' ";
}
echo "<tr " . $class . " id='" . $row['NAME'] . "'>";
...
}