Embed PHP in Javascript - javascript

I need to embed PHP into Javascript so that when the user selects Countries it would display the result from the query alphabatically and if he selects Numbers then list based on numbers in descending.
Having researched, I have applied this (echo concept into my code) but doesn't seem to work.
I have the following query written in PHP that output staffs' country of birth( no of staff born in number of countries) in ascending order:
$querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) ASC ";
Then, I have a dropdown in HTML:
<form>
<label for="sortorder">Sort by:</label>
<select id="sortByDropdown" onchange="sortBy(this);">
<option value="alphabatically">Countries</option>
<option value="numbers">Number</option>
</select>
</form>
Furthermore, I have a Javascript function sortBy()
function sortBy(){
var sortByDrpdownDiv = document.getElementById('sortByDropdown');
if (sortByDrpdownDiv[sortByDrpdownDiv.selectedIndex].value == 'numbers'){
alert("yo in if statement");
<?php $querytest = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC ";
$result = mysql_query($querytest);
while ($row = mysql_fetch_assoc($result)) {
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}?>
document.getElementById('staffbirthplaces').innerHTML = <?php echo $row?>;
}
}
First I am going only for Numbersbecause the same logic will apply to the Countries. Any help will be appreciated

So, i finally did it! Used switch instead of IF statement. Below is the code:
function sortByAlphabetsOrNumbers(obj){
var selectedValue = obj.options[obj.selectedIndex].value
switch(selectedValue)
{
case "numberOfStaff":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$staffNumbersDesc = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x order by count(*) DESC";
$result = mysql_query($staffNumbersDesc);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
case "countries":
document.getElementById('sortBy').innerHTML =
"<?php
include 'connection.php';
$alphabaticalOrder = "select x , COUNT( * ) from( select `staffbirthplace` as x from staffbirthdetails where staffemailid IN(SELECT staffemailid FROM staff where orgid='" . $orgId . "' AND deptname='" . $deptName . "' AND teamname='" . $teamName . "') ) as temptable group by x";
$result = mysql_query($alphabaticalOrder);
while ($row = mysql_fetch_assoc($result))
{
echo "<b>";
echo $row['x'];
echo ": </b> ";
echo $row['COUNT( * )'];
echo "<br/>";
}
?>";
document.getElementById('birthCountriesAlphabaticalOrder').style.display = "none";
break;
}
};
Hope it helps someone

Related

Connection of two tables

I have a problem with making a query to MYSQL which will combine two tables.
Mainly I want to through such a query
<?php
require_once 'dbconnect.php';
$wynik = mysql_query("SELECT * FROM users")
or die('Błąd zapytania');
/*
wyświetlamy wyniki, sprawdzamy,
czy zapytanie zwróciło wartość większą od 0
*/
if(mysql_num_rows($wynik) > 0) {
/* jeżeli wynik jest pozytywny, to wyświetlamy dane */
echo "<table cellpadding=\"2\" border=1>";
while($r = mysql_fetch_assoc($wynik)) {
echo "<tr>";
echo "<td><a href='pokaz.php?id=".$r['userId']."'>".$r['userName']."</a></td>";
echo "</tr>";
}
echo "</table>";
}
?>
and after clicking on the link, the pictures that this user added showed me
the file pokaz.php looks like this
my tables
Please, let someone ask me this question, I will be grateful
use mysqli:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$wynik = mysqli_query($con, "select `user`.userId, `user`.userName, `pictures`.image_name from `user` inner join `user_uploads` on `user_uploads`.user_id_fk = `user`.id");
/*
wyświetlamy wyniki, sprawdzamy,
czy zapytanie zwróciło wartość większą od 0
*/
if($wynik) {
if (mysqli_num_rows($wynik) > 0) {
;
/* jeżeli wynik jest pozytywny, to wyświetlamy dane */
echo "<table cellpadding=\"2\" border=1>";
while ($r = mysqli_fetch_assoc($wynik)) {
$imgName = $r['image_name'];
echo "<tr>";
echo "<td><a href='pokaz.php?id=" . $r['userId'] . "'>" . $r['userName'] . "</a></td>";
echo "<img src='/uploads/$imgName' />";
echo "</tr>";
}
echo "</table>";
}
}
?>
UPDATE:
if you want to show images in pokaz.php for each user:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$wynik = mysqli_query($con, "select `user`.userId, `user`.userName, `pictures`.image_name from `user` inner join `user_uploads` on `user_uploads`.user_id_fk = `user`.id");
/*
wyświetlamy wyniki, sprawdzamy,
czy zapytanie zwróciło wartość większą od 0
*/
if($wynik) {
if (mysqli_num_rows($wynik) > 0) {
;
/* jeżeli wynik jest pozytywny, to wyświetlamy dane */
echo "<table cellpadding=\"2\" border=1>";
while ($r = mysqli_fetch_assoc($wynik)) {
$imgName = $r['image_name'];
echo "<tr>";
echo "<td><a href='pokaz.php?id=" . $r['userId'] . "'>" . $r['userName'] . "</a></td>";
echo "<img src='/uploads/$imgName' />";
echo "</tr>";
}
echo "</table>";
}
}
?>
pokaz.php
<?php
if(isset($_GET['userId'])){
$userId = $_GET['userId'];
$con = mysqli_connect("localhost","my_user","my_password","my_db");
$query = "select image_name from user_uploads";
$result = mysqli_query($con, $query);
if($result){
while($row = mysqli_fetch_assoc($result)){
$imgName = $row['image_name'];
echo "<img src='/uploads/$imgName' /></br>";
}
}
}

Update php SQL when checkbox check (no submit button)

I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);

how to export html table to excel, with pagination

I have a form which displays mysql data in the form of an HTML table, using pagination of 5 records per page. I'm trying to export my table to excel, but it's only exporting data of the rows that are currently show, meaning if there are 20 rows, it only shows the first 5 as those get displayed. How can I make it export the one's that are not being displayed but still part of the search? I saw a few other people with a similar question but none have answers( How to export all HTML table rows to Excel file from a paginated table?). Hopefully I can get one!
<?php
if(isset($_GET['submit']) || isset($_GET['page'])){
// Setting up the Pagination below
echo '<center>';
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_query .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($end_loop > $total_pages){
$end_loop = $total_pages;
}
if($difference > $total_pages){
$end_loop = $total_pages;
}
echo '<div class = "center">';
echo '<div class = "pagination">';
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1".$urlparameter."'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1).$urlparameter."'> << </a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i.$urlparameter."'>".$i."</a>";
}
if($page < $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1).$urlparameter."'> >> </a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages.$urlparameter."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</div>';
echo '</div>';
echo '<br>';
$sql = "SELECT Name, SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page ";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
echo '<br>';
?>
// This is what is getting the current rows, but not all
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table').outerHTML));" value = "Export into excel" />
<?php
}
?>
UPDATE: Found the answer I was looking for I simply ran a new sql query without the LIMIT clause and stored it in a hidden table. I then use the hidden table to export data
// SQL and hidden table for exporting to excel
$page_query2 = "SELECT * FROM tbl_call_log_detail ";
$page_query2 .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ORDER BY TIME DESC ";
$page_result2 = mysqli_query($conn, $page_query2);
$row2 = mysqli_num_rows($page_result2);
$all_property2 = array();
echo "<table class = 'data-table2' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table2' hidden>
<tr class = 'data-heading2'>";
while($property = mysqli_fetch_field($page_result2)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property2, $property ->name);
}
echo '</tr>';
while ($row2 = mysqli_fetch_array($page_result2)){
echo '<tr>';
foreach($all_property2 as $item){
echo '<td> '. $row2[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
?>
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table2').outerHTML));" value = "Export into excel" />
<?php
}
?>
You can use JQuery table2excel plugin following is the link
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
Try following code pen to only JavaScript
https://codepen.io/kostas-krevatas/pen/mJyBwp

How to change quantity with php and plausible js?

Okay so I have this problem on a site im working om.. some merchandise that have been selected are POST'ed from a form to this page. Then the prices are gathered from the db and it all gets added to get the total sum price.. However I need to get a function where you can change the quantity of the items selected.
The code I have so far is this - For displaying the selected products.
$t_id=implode(',',$t_id);//impload the value with the ',' and used IN operate to get all the value relate this id (11, 19 and 20)
$query = "SELECT * FROM tilbehor WHERE t_id IN ($t_id)";
$result = $db->query($query);
$num_rows = $result->num_rows;
if($num_rows > 0) {
while($row = mysqli_fetch_array($result)) {
echo "
∙ <input type='text' style='width: 50px;' name='quantity' id='quantity' class='txt' value='1'> - <b>".$row['tilbehor_navn']."</b><br>
";
}
} else {
echo "Error";
}
And here is the code to display and add up alle the prices.
$test = $_POST['tilbehor'];
$test=implode(',',$test);//impload the value with the ',' and used IN operate to get all the value relate this id (11, 19 and 20)
$query = "SELECT * FROM tilbehor WHERE t_id IN ($test)";
$result = $db->query($query);
$num_rows = $result->num_rows;
if($num_rows > 0) {
$number = $p_pris + $o_tilbehor_pris;
while ($row = mysqli_fetch_array($result)) {
$number += $row['kunde_pris'];
}
$output = $number;
$followers = number_format( $output , 0 , '.' , '.' );
echo "
<br>
<input type='checkbox' name='price' value='$followers'>Kunde pris $followers<br>
";
} else {
$number = $p_pris + $o_tilbehor_pris;
$output = $number;
$followers = number_format( $output , 0 , '.' , '.' );
echo $followers;
echo ",-";
}
Anyone have any idea on how to code it so you can change the quantity of an item and so that the price is affected as well? :)

button onclick= returns var without slashes

The following code returns the $userurl, that is:
<button class="Urllink" type="button" onclick="window.parent.location.href=" www.facebook.com";"><img src="http://www.facebook.com/favicon.ico" width="16" height="16">Facebook</button>
CODE:
function userUrl($user){
include ('bin/mysqllogin.php');
$userUrl = '';
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href="';
$userUrl .= $dbresult['Url'] . '";><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
As you all see $userUrl returns not the needed http://www.facebook.com. What am I doing wrong here?
Edit1: Found the solution. I needed to add /' around the var $dbresult['Url']. So the code changed to:
function userUrl($user){
include ('bin/mysqllogin.php');
$userUrl = '';
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href=\'';
$userUrl .= $dbresult['Url'] . '\';"><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
You need to prepend http:// to $userUrl. As such:
function userUrl($user) {
include ('bin/mysqllogin.php');
$userUrl = 'http://'; // <-- Prepended in here
$query = "SELECT * FROM urls WHERE Usernaam = '$user'";
$result = mysqli_query($dbc, $query);
if (!$result) {
echo ' Query Failed ';
}else{
if (#mysqli_num_rows($result) >= 1) {
while ($dbresult = mysqli_fetch_assoc($result)){
$userUrl .= '<p class="Link_par"><button class="Urllink" type="button" onclick="window.parent.location.href="';
$userUrl .= $dbresult['Url'] . '";><img src=' . $dbresult["UrlIcon"] . ' width="16" height="16">' . $dbresult["UrlName"] . '</button>';
}
}
}
mysqli_close($dbc);
return $userUrl;
}
Please lookup SQL-injections by the way. Or, best choice, use PDO.

Categories

Resources