Having a slight problem here. I'm trying to create an admin side function to delete FAQ's, and despite the fact that I got a script working, I need to figure out how to automate a [WHERE clause] per added question.
To describe it, every question gets posted and has an ID in the database. I want to delete on that ID, but per question I add the
DELETE FROM faq [WHERE faq_id=#]
My current code:
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($faqResult = mysql_fetch_array($queryresult)){
$faqQuestion = $faqResult['question'];
$faqAnswer = $faqResult['answer'];
echo "<p class='faqQuestionAdmin'>$faqQuestion</p>" .
"<p class='faqAnswerAdmin'>$faqAnswer</p>" .
"<a class=faqDelete>X</a>";
}
if(mysql_num_rows($queryresult) <= 0) {
echo("<div><p>No Questions available</p></div>");
}
mysql_free_result($queryresult);
mysql_close($conn);
that serves as the deleting button. I was thinking a get function, but does anyone know how can I do this? Currently the only columns in the database for each question is the ID, question, and answer.
Thanks in advance!
If you have in the database:
Id | Question
--------------------------
1 | This is a question
2 | This is question 2
And when you render your page and have a own delete page
<?php
//You have get the questions by a query and stored in the local $sqlResults
echo "<table>
<tr><th>Id</th><th>Question</th><th>Delete</th></tr>";
foreach($sqlResults as $result)
{
echo "<tr><td>" . $result["id"] . "</td><td>" . $result["question"] . "</td>";
echo "<td><a href='your-domain.com/delete.php?id=" . $result["id"] . "'>X</a></td></tr>";
}
echo "</table>";
?>
And when you have a javascript function which makes a AJAX post call, make the href like:
yourDeleteJavascriptFunction(" . $result["id"] . ")
In both cases you render a list, and per item you add the id of the question. You can get the value when you receive the id and delete only that question by his id ;-)
If you want to avoid AJAX, you could simply put a link in your anchor tag to php file with GET variable in it:
X
Than in deleteFAQ.php you use
$id = $_GET['id'];
$query = "DELETE FROM faq WHERE faq_id=$id";
best way you can use ajax call and call php file and pass id to that file and write delete query in that php file
Related
Im creating a forum for a little project of mine.
So far I have been able to get the form contents and use php to process (YES I HAVE NOT ACCOUNTED FOR SQL INJECTION).
Anyway, the php code is as follows:
test.php
<?php
if (isset($_POST["add"])){
// "Save Changes" clicked
$title = $_POST['title'];
$message = $_POST['message'];
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$dt = date('Y-m-d h:i:s');
$sql = "INSERT INTO threads (title,author,date_posted,post) VALUES ('$title', 2, '$dt', '$message')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
header('Location: http://127.0.0.1:5500/RuneScape_website/RS.com/aff/runescape/forums/ForumThread/~tm10CE.html');
}
?>
Now what I really want to do, is after this data has been saved to the database, I want to display the newly created blog comment to the direct page on load up. For example, When you click submit, the comment should appear in the directed html page.
The only way I think about it, is that I need either javascript to create a new attribute and append it to the list of existing attributes (e.g. ), or in the php create the div and use javascript/JQuery to access the php file and collect the html.
So I want the $title and $message to be used in the html page where its directed to.
A real example is like stack overflow. After I write an answer the page appends my response. This is what I want to achieve.
I'm curious how to go about this. Thanks :)
Don't you need to know which forum page this submitted comment belongs to?
If you add a column to threads table and store the name of the forum page in it (in this case: ~tm10CE.html), then from your html page, you can make an ajax call to a php file and include the name of the page as a querystring value. Inside the php file, query the threads table for the name of the page and return all the entries related to that page.
I'm trying to create a website where I create dropdown menus filled by an SQL query and based on choices I make, different kinds of dropdown menus will appear.
I'm currently on my second dropdown menu which works, if I hardcode a certain value in there, but doesn't work if I try to use a dynamic value based on the user's selection.
Since I need to figure out what the user is selecting, and based on that, make a new dynamic selection, I tried getting the user-based info with javascript. Since I'm still very new to this, I tried saving that info to a cookie and then reading it with PHP to create a new list, but that didn't work the way I intended. It didn't update the page without a refresh, so I searched on and found AJAX.
With it, I was able to get the user selected dropdown info and send it back to PHP, which I need to do, because I need to run a new SQL query based on user's selection. And here is where I've completely ran out of ideas.
When I use AJAX and look at my browser's console, the supposed new dropdown menu is there in the console, but it just shows up as a blank dropdown menu on the webpage $varClass = $_POST['valitudKlass']; but if I set $varClass manually, then the script works great and generates me the list.
This is my function than runs whenever the user selects something in the first dropdown menu. It's supposed to get the value of the currently selected dropdown item and send it to pass.php
function valiKlass() {
var valitudKlass = $("#klass option:selected").text();
$.ajax({
type: "POST",
url: 'pass.php',
data: {valitudKlass : valitudKlass},
success:(function(data){
console.log(data);
})
});
$("#valiNimi").load("pass.php");
}
This is pass.php that's supposed to receive the information about what the user selected, then based on that, send a new SQL query and generate a new dropdown list:
<?php
require_once "config.php";
echo "Vali nimi;";
echo "<select name='nimi' id='nimi'>";
$varClass = $_POST['valitudKlass'];
$sql = "SELECT DISTINCT firstname FROM `students` WHERE class = '$varClass'";
$result = mysqli_query($connection,$sql);
while ($row = mysqli_fetch_array($result)){
echo "<option value ='" . $row['firstname'] . "'>" . $row['firstname'] . "</option>";
}
echo "</select>";
?>
I have only coded in C# in the past, so I'm completely new to both PHP and javascript, which I picked up a few days ago in order to help out some people I know, but this problem is slowly overwhelming me. I'd like to overcome it, so I appreciate any help you could give me.
Your $.ajax call sends the value to the server, your load() call doesn't.
Just put the result from the $.ajax in your page and remove the load() call.
$.ajax({
type: "POST",
url: 'pass.php',
data: {valitudKlass : valitudKlass},
success:(function(data){
$("#valiNimi").html(data);
})
});
Build the entire select in a variable before echoing it.
require_once "config.php";
$sendback = 'Vali nimi;<select name="nimi" id="nimi">';
$varClass = $_POST['valitudKlass'];
$sql = "SELECT DISTINCT firstname FROM `students` WHERE class = '$varClass'";
$result = mysqli_query($connection,$sql);
while ($row = mysqli_fetch_array($result)){
$sendback .= "<option value ='" . $row['firstname'] . "'>" . $row['firstname'] . "</option>";
}
echo $sendback . '</select>';
This question already has answers here:
Row count with PDO
(21 answers)
Closed 6 years ago.
I'm writing a small script to retrieve yarn details from database. I use a ajax live search script to retrieve data from the database the basic while loop function works but I want to handle the empty results by submitting a massage to the results div tag.
I did went through the first post which was made about this matter but it didn't solve my problem that's why I ask this from the stacks community. And my problem is not about getting the row count my problem is why the if command is not working.
So in order to that I use the below PHP script.
$searchString = "SELECT yarnId FROM yarndetails WHERE yarnId LIKE concat('%',:searchStr,'%')";
$dbSql = $dbConnect->prepare($searchString);
$dbSql -> bindParam(':searchStr', $_GET["q"]);
$dbSql -> execute();
$getCount = "SELECT COUNT(*) FROM yarndetails WHERE yarnId LIKE concat('%',:sStr,'%')";
$dbCount = $dbConnect->prepare($getCount);
$dbCount -> bindParam(':sStr', $_GET["q"]);
$dbCount -> execute();
$dataCount = $dbCount -> rowCount();
if($dataCount = 1){
while($row = $dbSql -> fetch(PDO::FETCH_ASSOC)) {
echo $row['yarnId'] . "\n";
}
}else{
echo "No Data";
}
I searched StackOverfllow and found out best way to count the rows is to use that "SELECT count(8).." statement but there's something wrong with it some how the if condition passes through directly to the while loop.
Is there a better way to do this or am I missing something if can help please.
$sql = "SELECT yarnId FROM yarndetails WHERE yarnId LIKE ?";
$stmt = $dbConnect->prepare($sql);
$stmt->execute(['%'.$_GET["q"].'%']);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($data){
echo json_encode($data);
}else{
echo "No Data";
}
Given you are using it for AJAX, the condition is essentially superfluous too, as it should be a no-brainer to tell an empty array in JS. Making the last 5 rows just
echo json_encode($data);
I am having issues with displaying my database products from a certain category when I click a link that calls a script function.
<li><button onclick="GPUclick()">GPU</button></li>
This is where I call my script to filter my products only to graphics cards, and I have that done with script / html like so:
function GPUclick() {
document.getElementById("parts").innerHTML = "<main> " +
" <img src='Images/760_ASUS.png' class='myClass'> " +
" <span class='myClass2'><ul><li>Asus GeFroce GTX 760</li><li>PCI-E 3.0, 2048MB VRAM</li><li>Price: £161.99</li></ul></span> "+
" <img src='Images/outOfStock.png' class='myClass3' alt='No stock'> " +
"</main>";
}
however now that I am using a database I need to filter through products that are being added into the database instantly.
I have a mysqli query that deals with the SQL:
$test = mysqli_query($conn, "SELECT * FROM products WHERE Category_ID = 2
I am just struggling now with printing anything out relating to that SQL command, I can do a in the javascript but that isn't really leading me to anything I can use or figure out without help and after looking for a while I can't find anything to help me either.
I appreciate any help / pushes in the right direction, thanks in advance.
I have tried adding "<?php echo $test['product_ID']?> " + to my JS function but that either outputs nothing or breaks the JS from even working.
You cannot use PHP in Javascript;
All PHP content must be in a PHP file and PHP is serverside, so all PHP is proceed on the Server.
In php use echo $test; or i would try this Php code:
<?php
echo "<script> var test = $test </script>"
?>
I'm new with questions and generally with "Stack Overflow", so forgive me if it is not formatted well.
So, I have problem with transferring some informations from one page to another. It is a value of <a> tag from an php while loop.
At the moment I have something like this:
$query = mysql_query("SELECT DISTINCT `a`.`id`,`o`.`first_name` , `o`.`last_name` , `a`.`name` FROM `owner` AS `o` , `animal` AS `a` WHERE `o`.`id` = `a`.`fk_current_owner` AND `o`.`fk_user` = '".$_SESSION['user_id']."'");
while($row = mysql_fetch_assoc($query)){
$pet_id = $row['id'];
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$pet_name = $row['name'];
echo 'Owner: <strong>'.$first_name.' '.$last_name.'</strong> ';
echo 'Pet: <strong>'.$pet_name.'</strong><br>';
}
So you can assume that this will display names of pets that logged user got.
So I linked their names and I need to get ID of selected name on another page so I can display details of pet on page viewPet.php.
You can also send the pet id along as a GET parameter with the link.
echo ''.$pet_name.'';
On the viewPet.php page you'd access it by $_GET['id']
you can put the link in a cookie:
setcookie(name, value, expire, path, domain);
that is the code to set the cookie and then to receive the cookie you can do $_COOKIE['name'];
or you can do a session.
session_start();
$_SESSION['name']=value;