When clicking on a link I open a modal window, there is a drop down menu, an item is selected and then when submitted I need to know which link was clicked that opened the modal so I can insert the information into the database. The only problem I am having is knowing which link opened the modal. Here is some snipets of my code:
collections.php:
<?php
$query = 'SELECT Song.Song_OID As Song_OID, Song.Title As Song,
Album.Album_OID As Album_OID, Album.Title As Album,
Artist.Artist_OID As Artist_OID, Artist.Name As Artist
From Song
Left JOIN Artist_has_Song ON Artist_has_Song.Song_Song_OID = Song.Song_OID
Left JOIN Artist ON Artist.Artist_OID = Artist_has_Song.Artist_Artist_OID
Left JOIN Album_has_Song ON Album_has_Song.Song_Song_OID = Song.Song_OID
Left JOIN Album ON Album.Album_OID = Album_has_Song.Album_Album_OID
ORDER BY Song, Artist IS NULL, Artist, Album IS NULL, Album';
$statement = $pdo->prepare($query);
$statement->execute();
while ($row = $statement->fetch(PDO:: FETCH_ASSOC)) { ?>
<tr>
<td>+</td>
</tr>
<?php } ?>
The link + is what is clicked to open this modal window:
<div id="addToPlaylist">
<div class="hidden">
X
<form action="addTo.php" method="post">
<p>Add To:</p>
<select name="userPlaylists">
<?php
$query = 'SELECT Name, Playlist_OID FROM Playlist WHERE User_User_OID=?';
$statement = $pdo->prepare($query);
$statement->execute(array($_SESSION['User_OID']));
while ($row = $statement->fetch(PDO:: FETCH_ASSOC)) {
?>
<option value="<?php echo $row['Playlist_OID']; ?>">
<?php echo $row['Name']; ?></option>
<?php } ?>
</select>
<input type="submit" value="Add"/>
</form>
</div><!-- end hidden -->
</div><!-- end addToPlaylist -->
This form then submits and this is the addTo.php:
<?php
require ('../private_html/config.php');
$playlist = $_POST['userPlaylists'];
$song = $_POST['< the part i dont know >'];
$query = 'INSERT INTO Playlist_has_Song (Song_Song_OID,
Playlist_Playlist_OID)
VALUES (?, ?)';
$statement = $pdo->prepare($query);
$statement->execute(array($playlist, $song));
header('Refresh: 0; URL=collections.php');
?>
The config.php file that is required has the session start as well as the pdo. So given this set up i need to get the Song_OID from the loop that has the #addToPlaylist link into the addTo.php so it can be inserted into the playlist. Any help will be greatly appreciated.
Due to the fact that you also tagged this question as HTML5, you might be interested in using data attributes.
This would allow you use the following HTML:
<tr>
<td>
<!-- class song-picker is used to allow for easier element selection -->
+
</td>
</tr>
and you could use jQuery to grab the song's id
var songID;
$('.song-picker').on('click', function (e) {
songID = $(this).data('song-id');
});
This might need some improving, but might server you as a good staring point.
Related
I have a delete button which when clicked it prompts user for conformation. It suggets it is working but when I check the database the data is still there.
How do I get my delete button to remove data from the database?
<?php
// build query
$sql= "SELECT blogID, title, made_by, description FROM blogs";
// execute query
$res=$mysqli->query($sql);
// get multiple results
while($row = $res->fetch_assoc()){
$blogID=$row['blogID'];
$title=$row['title'];
$made_by=$row['made_by'];
$description=$row['description'];
?>
<form action = "post_action.php" method="POST">
<div style="text-align:left">
<div class="row">
<div class="leftcolumn">
<div class="card">
<td><?php print($title);?></td><br>
<td> <?php print($description);?> </td> <br>
<td><?php print($made_by);?> </td><br>
<?//Create edit, comment and delete buttons for each blog?>
<button onclick="window.location.href = 'edit_blog.php';">Edit Blog </button>
<input type = "hidden" name="blogID" value= "<?php print($blogID);?>" >
<input type="submit" name="action" value="Insert Comment"/>
<input type="submit" onclick="deleteme(<?php echo $row['blogID']; ?>);" name="action" value="Remove Blog"/>
<? //Javascript code?>
<script language="javascript"> //inserts javascript code
function deleteme(delid)
{
if(confirm("You're about to delete this blog. Click OK to continue or click cancel.")){ //opens an alert window asking the user if they're they want ot remove the blog
window.location.href='post_action.php?del_id=' +delid+''; //If they click OK then it'll run the delete function on post_action.php
return true;
}
}
</script> <?//ends javascript code ?>
</form>
</div>
This is post_action.php
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_POST['blogID']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
Because you did not execute your delete action. Execute your delete query to remove the data to your database.
$mysqli -> query($query)
The problem is in $_POST['blogID'].
You are redirecting the user and passing the blog id in the query string, so it should be $_GET. Also the key is del_id and not blogID.
So in post_action.php, do
<?php
include("_config.php");
debug($_POST);
if($_POST['action'] == "Remove Blog"){
$query = "DELETE FROM blogs WHERE blogID={$_GET['del_id']} LIMIT 1";
header ("Location: blog_test.php");
}
?>
PS: I am really worried about if you should delete something this way.
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.
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;
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.
You know when you are entering your personal information on a form, and you get to the state drop down box, most of the time you can type I and it will go right to the states that begin with I.
I am wanting to do the same thing here. My drop down box displays a list of options for a user to choose from. If they want to choose an option that starts with B I would like them to be able to type B and it will bring up the first option that starts with a B hopefully this is clear.
Here is the code
$sql = "SELECT iro_option, iro_desc from incrateopt
WHERE iro_div = ".$divnmbr."
AND iro_option NOT IN (
SELECT cm_optnum
FROM cmopt
WHERE cm_serialno = '".$serialno."'
)
AND CHAR_LENGTH(iro_desc) > 0
ORDER BY iro_desc ASC";
$result=$link->query($sql);
echo $link->error;
$ct = 1;
while($r=$result->fetch_array()):
$opnum = $r["iro_option"];
$opdesc = $r["iro_desc"];
$opdata[$ct] = $opnum." ".$opdesc;
$ct++;
endwhile;
$usearray = "opdata";
?>
<div style="font-weight: heavy;">
<tr>
<td>
<select name="Oparr" multiple size=7 valign=top STYLE="width: 500px;" <? echo $Oparr; ?>>
<?
foreach ($$usearray as $value):
echo "<option value='".$value."'>".$value."</option>\n";
endforeach;
?>
</select>
</td>
</tr>
I would imagine that you would do it in the select name some kinda of onkeypress function.
THANKS STACK!