JScript within php - javascript

The below code included in php file and gets data from data base
$sqlUrl = "SELECT *
FROM $category
WHERE sub_category = '$subCategory'";
$result = mysqli_query($con,$sqlUrl);
now I need to display those data on the screen and thus I would like to load them on am html file in a specific division
<div id="div6">
</div>
I think that I can do it using JScript but I don't know how to do it

What the ... If you just want to print it, you dont need JavaScript:
<div id="div6">
<?php foreach($result as $r) {
echo $r;
} ?>
</div>

why you want to display results with JScript? You can do it like this also:
<div id="div6">
<?php
while ($row = mysqli_fetch_assoc($result)) {
echo $row["Name"]."<br />";
}
?>
</div>
for more details Plese refer: http://in1.php.net/mysqli_fetch_assoc

Related

Prepared statement to make pictures show up on php page, when JOINING tables

I currently have a loginsystem where a user is able to register and login as a user.
My system is based on PHP PDO.
When the user is logged in they should be able to upload a picture which is linked to their account.
Right now i have a fully functional loginsystem so thats great, and the user is currently able to upload a picture to the database, but he cant yet see it on the site.
Right now my problem is to make the pictures show up on the site.
I want the user to be able to see his OWN pictures that he uploaded, and not anybody elses pictures.
This is what i have so far! :)
This my Database!
TABLE PICTURES with the following rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
TABLE USERS with the following rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my CODE so far:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.INC.PHP
<?php
include "../upload.php";
//Find the ID of the USER
// session_start();
include_once 'dbh.inc.php';
$pictureTitle = ($_POST["filetitle"]);
$pictureText = ($_POST["filedesc"]);
//Fnd ID from the user
//$user = $_SESSION["u_id"];
$user = $_SESSION['u_id'];
$queryUserID = 'SELECT user_id from '.'users'. ' where user_name="'. $user.'";';
$stmt = $conn -> prepare($queryUserID);
$stmt -> execute();
$result = $stmt -> fetch(PDO::FETCH_ASSOC);
//FileDic
$fileDirectory = "../uploads/";
$fileHandled = $fileDirectory . basename($_FILES["file"]["name"]);
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileHandled)) {
//echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
$picture = 'INSERT INTO pictures (titlePicture, descPicture, userid, imageFullNamePicture)
VALUES (:titlePicture, :descPicture, :userid, :imageFullNamePicture);';
$stmt = $conn->prepare($picture);
$stmt -> bindParam(":titlePicture", $pictureTitle);
$stmt -> bindParam(":descPicture", $pictureText);
$stmt -> bindParam(":userid", $user);
//$stmt -> bindParam(":userid", $result['user_id']);
$stmt -> bindParam(":imageFullNamePicture", $fileHandled);
$stmt -> execute();
header("Location: ../upload.php?`Success");
?>
<?php } else {
header("Location: ../upload.php?Error");
//echo "Sorry, there was an error uploading your file.";
}
header("Location: ../upload.php");
UPLOAD.PHP
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="includes/upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['users'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="pictures">
<a target="file" href= <?php ?>>
<img class="pic" src= <?php echo $data['imageFullNamePicture']; ?>></a>
<div class="titlePicture"><?php echo $data['titlePicture']; ?> <br> </div>
<div class="descPicture" >Your description:</div>
<div class="text"><?php echo $data['titleDesc']; ?> <br> ?> </div>
</div>
<?php
}
};
?>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
So yea the problem is that i cant get the pictures that connects to the currently logged in user to show up on the page upload.php
I hope that somebody can help me! :)
EDIT!!!:
So i currently have this piece of code. IT should make the user see the pictures that he uploaded to the database, but it is very buggy. And it only shows one picture per user. Can somebody help make this work.
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic)
?>
<figure id="<?php echo $pic['id']; ?>">
<b><figcaption><?php echo $pic["titlePicture"] ?>
<img src = <?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
<?php
// }
}
?>
</div>
Your fetching the data as numerically indexed arrays PDO::FETCH_NUM, yet your using the keys in your code:
UPLOAD.INC.PHP
//instead of PDO::FETCH_NUM
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
...
<?php echo $data['imageFullNamePicture']; ?>
...
<?php }
Use PDO::FETCH_ASSOC instead.
Please don't do this with PDO:
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
If someone manages to get data in here name="' . $_SESSION['u_id'] . '" you've just defeated the whole purpose of preparing your SQL. It shouldn't matter where that data came from, you never know when a simple coding mistake or something will allow user data into a session variable.
$user_data = 'SELECT * FROM users INNER JOIN pictures on users.user_id
= pictures.userid WHERE name=:u_id';
$stmt = $conn->prepare($user_data);
$stmt->execute(['u_id'=>$_SESSION['u_id']]);
It's that easy to prepare it properly. You don't really need to even use bind whatever with PDO, unless you wan't to restrict the Type. But I think it's also the only way to do LIMIT :limit. Anyway I almost never use them. In general both PHP and MySQL are smart enough to do the proper type casting.
PS. don't forget to call session_start() if your using $_SESSION or none of that will work. I didn't see it in the code that was posted, so I have to mention it.

Variable assigned to HTML input's value through PHP is not understood by JS script

I'm working on a project of a website which shows a chart. User should be able to change a displayed chart (without changing the website) by clicking one of 'Available sensors' from dropdown options. Dropdown connects to MySQL database with used sensors. The sensor's id is assigned to HTML-input ID and its name is assigned to input value.
My intension is to use sensor ID in another data.php file which is responsible for connecting to tables (MySQL) with data collected by sensors. This ID would tell to which of the tables this programm should connect.
At the moment JS script's task is to alert an ID of the chosen sensor when it's clicked on the dropdown menu. Instead of a number I get a message saying 'undefined'. Eventually it would transfer the stored id to the mentioned data.php file.
Could you please tell me whether it's necessary to use AJAX in this case or what's a possible reason of this error in my code?
I also tried to use button insted of input. When clicking on sensors names on dropdown I've received only messages with '1'. However assigning sensorName worked out in both cases. Sensors ID is stored as INT, name as VARCHAR in MySQL table.
Thank you in advance for your help :)
<div id="header_btn" class="dropdown">
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?>
<input onclick="changeSensorID(this.value)" onmouseover="this.style.textDecoration='underline'" onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>" value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script>
function changeSensorID() {
var sensorID = document.getElementsByClassName("btn_drop").id;
alert(sensorID);
};
</script>
</div>
please check this code, working fine
<input type="submit" id="btn" value="Available sensors" class="btn btn-success" />
<div class="dropdown-content">
<?php
include("config.php");
$sql = "SELECT * FROM sensors";
$result = $db->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$sensorID = $row["id"];
$sensorName = $row["WebName"];
?><input onclick="changeSensorID(event)" onmouseover="this.style.textDecoration='underline'"
onmouseout="this.style.textDecoration='none'" class="btn_drop" id="<?php echo $sensorID ?>"
value="<?php echo $sensorName ?>" /></a>
<?php
}
}
?>
</div>
<script >
function changeSensorID(event){
var sensorID = event.target.id;
alert(sensorID);
}
</script>
</div>
getElementsByClassName returns array of at least one item if found any. You have to provide index of element that you want to use.
Example
var sensorID = document.getElementsByClassName("btn_drop")[0].id;

PDO fetch then targeted object?

I currently have a page where I'm connecting to db via PDO, db, prepare.
Selecting SQL_CALC_FOUND_ROWS in order to have pagination with the results.
All of that is good. However, each return is to have a text popup when clicked. Thats where I want to target a particular field of defined row.
Code I have is as follows :
$db = new PDO('mysql:dbname=###;host=###','###','###');
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ?(int)$_GET['per-page'] : 8;
//Positioning
$start = ($page > 1) ? ($page * $perPage) - $perPage : 0;
//Query
$articles = $db->prepare("
SELECT SQL_CALC_FOUND_ROWS id, comment_caption, comment_sub_caption,comment_title, comment_main, comment_name,
comment_date, comment_url
FROM TABLE_NAME
LIMIT {$start}, {$perPage}
");
$articles->execute();
$articles = $articles->fetchAll(PDO::FETCH_ASSOC);
// Pages
$total = $db->query("SELECT FOUND_ROWS() as total")->fetch()['total'];
$pages = ceil($total / $perPage);
//Pagination div
<div class="pagination">
<?php for($x = 1; $x <= $pages; $x++): ?>
<a href="?page=<?php echo $x; ?>&per-page=<?php echo $perPage; ?> "<?php if($page === $x){ echo 'class="selected"'; }?>><?php echo $x ?></a>
<?php endfor; ?>
</div>
// Here is the container for the foreach
<div id="container">
<?php
foreach($articles as $article): ?>
<div class="item small">
<div class="module">
<div class="article">
<div class="item-inner">
<a href="<?php echo $article['comment_url']; ?>">
<div class="project-title">
<div class="mid">
<h2><?php echo $article['comment_caption']; ?></h2>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
// This is the popup that I want to associate with each return
<div id="test-popup" class="white-popup mfp-hide">
<blockquote><?php echo $article['comment_main'];
?></blockquote>
<p><i><?php echo $article['comment_name']; ?> - <?php echo $article['comment_date']; ?></i></p>
</div>
In the popup, I want to echo the 'comments_main, comments_name & comments_date' field of the particular instance that is clicked. Here currently, it just echos the first row.
I'm not sure what the best way to go about it is... ?
Any help would be greatly appreciated.
This is not really a php-mysql related question, but rather a javascript-html-css related one.
You have 2 options:
You output the comments_main, comments_name & comments_date fields to all listed items in a way they are not visible to the users first in the browser. Typically, you could use the anchor element's title property, or html5's data- properties, or even a list of invisible divs. Whenever the user clicks a link, you use javascript to fetch these data for the given comment from your list on the client side (if they are not stored in a list of divs already) and make it appear.
You do not output these data to the client, but upon clicking you use an ajax call to retrieve these data from the server via another php page.
For both approach there are lots of tutorials out there with designed boxes (tooltips) and copy-paste javascript, html, and css code.

Calling PHP Variable from another file without the use of Session or Include

so I'm making a pagination which uses 3 different files. The page itself (index.php), the header which contains a JS Ajax scripts for changing page which is included in the index.php (header.php) and a pagination script contained in a separate PHP file which is called via the AJAX script (pagination.php).
In the index.php I have a variable which defines the category the user is currently in named $category, I would like this variable to be used in the pagination.php to select what results are shown (Only results where subcategory2 = $category).
Because pagination.php is called through an ajax script on document ready it can't see that variable. Is there any way for the two to communicate without the use of Session (which would mess up when changing to other categories) or include (which would end up calling the script twice).
Header.php:
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("/includes/pagination.php");
$(".pagination").bootpag({
total: <?php echo $pages; ?>,
page: 1,
maxVisible: 5
}).on("page", function(e, num){
e.preventDefault();
$("#results").prepend('<div class="loading-indication"><img src="/images/ajax-loader.gif" style="width: 2em; margin: 0 auto;" /><br />Loading...</div>');
$("#results").load("/includes/pagination.php", {'page':num});
});
});
</script>
Pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
//sanitize post value
if(isset($_POST["page"])){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
if(!is_numeric($page_number)){die('Invalid page number!');} //incase of invalid page number
}else{
$page_number = 1;
}
echo $category;
//get current starting point of records
$position = (($page_number-1) * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($mysqli, "SELECT ProductID, SupplierID, ProductName, ProductDesc, ProductURL, Image1URL, Image2URL, Image3URL, Image4URL, Image5URL, ProductCondition, Stock, AvailabilityDate, ProductGTIN, ProductMPN, ProductBrand, ProductGroupID, ProductColour, ProductGender, ProductAgeGroup, ProductMaterials, ProductSize, ProductPSize, Feature1, Feature2, Feature3, Feature4, Feature5, Feature6, Feature7, Feature8, Feature9, Feature10, CostPrice, Markup, Offer, Shipping, ShippingWeight, ShippingLabel FROM products ORDER BY productid ASC LIMIT $position, $item_per_page");
//output results from database
echo '<ul class="page_result">';
while($row = mysqli_fetch_array($results))
{
echo '
<table id="productbox">
<tr>
<th class="producthead" colspan="3">'.$row["ProductName"].'</th>
</tr>
<tr>
<td class="productimgcell"><img src="'.$row["Image1URL"].'" class="productimg" /></td>
<td class="productinfo">'.$row["Feature1"].'<br />'.$row["Feature2"].'<br />'.$row["Feature3"].'</td>
<td class="productprice"><div class="pricebg">'; echo price_calc($mysqli, $row["ProductID"], $row["CostPrice"], $row["Markup"], $row["Offer"]); echo '<span class="priceinfo">inc. VAT</a></div><div style="clear:both;"></div><div class="addtocartbg">Add To Cart</div></td>
</tr>
<tr>
<td class="productfoot" colspan="3">5/5 Stars - Write A Review</td>
</tr>
</table><br />
';
}
echo '</ul>';
?>
Index.php
<?php
$category = 'AMD';
global $category;
$page_title = 'AMD Motherboards - Motherboards - PC Components';
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
$results = mysqli_query($mysqli,"SELECT COUNT(*) FROM products WHERE SubCategory2 = '$category'");
$get_total_rows = mysqli_fetch_array($results);
$pages = ceil($get_total_rows[0]/$item_per_page);
include_once($_SERVER['DOCUMENT_ROOT'].'/template/header.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/template/sidemenu.php');
?>
<div class="contentboxcontainer">
<div class="centercontentbox">
<div class="halfcontentboxcontainer">
<div class="halfcontentbox">
<div class="contenthead">Deals</div>
<div class="content">
<div class="contentcontainer">
Test
</div>
</div>
</div>
</div>
<div class="halfimgcontentboxl">
<img src="https://assets.vg247.com/current//2015/07/battlefront_leaked_alpha_tatooine_4.jpg" style="border-radius: 5px; width: 100%;" />
</div>
</div>
</div>
<div class="contentboxcontainer">
<div id="contentbox">
<div class="contenthead">Products</div>
<div class="content">
<div id="results"></div>
<div class="pageswrap"><div class="pagination"></div> <div style="clear:both;"></div></div>
</div>
</div>
</div>
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/template/footer.php');
?>
Send the category id as a post variable in the load command.
var cat = <?php echo $category; ?>
$("#results").load("/includes/pagination.php", {'page':num , 'category':cat});
For anyone else interested in an answer for this, I'm going to post my work around just in case anyone might find it useful.
In my pagination.php I added a check for the current page the user is on and compared that to a url I define. If the user is on said page then I define the category there.
pagination.php
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/functions.php');
include_once($_SERVER['DOCUMENT_ROOT'].'/includes/db_connect.php');
if ($_SERVER['HTTP_REFERER'] == $domainurl.'/store/pc-components/motherboards/amd/') {
$category = 'AMD';
}
I had to use $_SERVER['HTTP_REFERER'] due to it being called from JS and $domainurl is defined in my config file (which is included in db_connect.php).
I can now call my variable in a mysql query on pagination.php
FROM products WHERE SubCategory2 = '".$category."'
Not the cleanest of work arounds but it saved me worrying about having to rethink the way I was doing it all.

Open remote page into bootstrap modal

Here is something that seems to be having repetition problem with. I want to open a content into a modal from a remote page, which is populated from a MySql database. I also want that modal to be opened with my custom styling etc. I have gone so far with it, but after that I have got stuck. Here is the code so far
the output on the page:
$output .='<h4><a class="md-trigger" data-OfferID="' . $offer_id . '" href="#" data-modal="offer_modal">' . $title . '</a></h4><hr>';
the modal where data is loaded, on click of output (located in footer.php):
<div id="offer_modal" class="md-modal md-effect-flip" aria-hidden="true">
<div class="md-content">
</div>
</div>
the script located in the page where $output is echoed:
$('.md-trigger').click(function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").html(result);
}});
});
and just as a reference, the remote page which loads the data based on id, and then populates modal:
<?php
extract($_GET);
?>
<?php
require('inc/connect/config.php');
$offer = (int) $_GET['OfferID']; ?>
<?php
try {
$code_sql = 'SELECT * FROM codes WHERE id LIKE :code_id';
$query = $db->prepare($code_sql);
$code_params = array(':code_id' => $offer);
$query->execute($code_params);
$code_r = $query->fetch(PDO::FETCH_ASSOC);
$c_title = $code_r['title'];
$c_desc = $code_r['description'];
$c_redeem = $code_r['redemption'];
$c_textcode = $code_r['textcode'];
$c_exp = $code_r['expiry'];
$c_terms = $code_r['terms'];
$c_url = $code_r['url'];
} catch (PDOException $e) {
echo "failed to load offer";
exit;
}
?>
<button type="button" class="close close-md" data-dismiss="modal" aria-label="Close"><h3><span aria-hidden="true">×</span></h3></button>
<h5><?php echo $c_title; ?></h5>
<p><?php echo $c_desc; ?></p>
<h3><?php echo $c_textcode; ?></h3>
<p><?php echo $c_redeem; ?></p>
<p class="small-text"><?php echo $c_terms; ?></p>
At the moment, the problem I am getting is the modal only loads once, when the top item in the list is clicked, it won't load when clicking any other item in the list... what am i doing wrong!! I am pretty new to all of this, so go easy on me please :)
thanks in advance
Kaylee
Test with this example.
$('.md-trigger').on('click',function(){
var OfferID=$(this).attr('data-OfferID');
$.ajax({url:"Open-Offer.php?OfferID="+OfferID,cache:false,success:function(result){
$(".md-content").empty().append(result);
}});
});

Categories