Database update fails to work within php - php

I have a fairly simple php page which displays a list of results from the database in a table, and the end of the row is a Dismiss button, I want to click this and have the database update to reset the flag which is original query thus dismissing the message.
I have looked at loads of examples here and have built a form around the button to call a separate php file which should execute the query to change the database and return to the original page which will be redrawn with one record less.
Everything works as expected but the database update doesn't occur.
Table drawing:
<table>
<!-- lay out the table and populate the header row -->
<tr>
<th>Site</th>
<th>Name</th>
<th>Alarm</th>
<th>Error</th>
<th>Confirm</th>
</tr>
<?php
$sql = "SELECT * FROM `hive_data` WHERE ack = 'y' "; //SQL query to find entries where the ack field is set 'y'
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) { //start while loop to draw table one line per returned row
$line = $row["row_id"]; //define page variables from table columns
$site = $row["site"];
$module = $row["module_id"];
$alarm = $row["alarm"];
$error = $row["error"];
?>
<tr>
<!-- display each row returned listing the fields lists and a box to dismiss the alert -->
<td><?php echo $site; ?></td>
<td><?php echo $module; ?></td>
<td><?php echo $alarm; ?></td>
<td><?php echo $error; ?></td>
<td>
<form action = "data/dismiss_alerts.php" method="post">
<!-- last column of the table is a dismiss button -->
<input type="hidden" value="<?php echo $line ?>" name="line"> <!-- hidden input to send the row number to be changed -->
<input type="submit" value="Dismiss"> <!-- submit button to post data to dismiss_alerts.php -->
</form>
</td>
</tr>
<?php
} //close the while statement
?>
</table>
Dismiss alert page:
if(isset($_POST['line'])) {
$rowToUpdate = intval($_POST['line']);
$sql = "UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = " . $rowToUpdate . "";
$result = mysqli_query($conn, $sql);
header('Location: ../index.php?page=home'); // return to sending page..
}
The execution refreshes the original page but the database is not updated.
Troubleshooting dismiss alert page:
if(isset($_POST['line'])) {
$rowToUpdate = intval($_POST['line']);
$sql = "UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = " . $rowToUpdate . "";
echo $sql;
if($conn->connect_error) {
echo "Connection failed";
} else {
echo "Connected";
if($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
}
}
The first if clause works fine so I stay on the dismiss alerts page and get the echo of my query and a message saying the database is connected but the second if clause never reports anything.
UPDATE `hive_data` SET `ack` = 'n' WHERE row_id = 253Connected
I have tested the query inline on the calling page so that it actually deletes the last line of the table on every refresh so I am pretty sure that bit works, but I am really stumped with this.
Any ideas?

OK so after spending all morning on this ten minutes after posting here I found that despite my troubleshooting line above the db was not connected I had to build a connect and disconnect into the page and it works fine.
Now to read up on prepared statements and re-do it all that way :-)

Related

$_GET doesn't work in my program and no lines beneath it are executed

I am trying to add a function to my website where it will add filters to a SQL select statement by allowing the user to enter text in some text boxes and clicking the filter button.
I haven't gotten as far as that because I'm having issues with the $_GET function.
The idea is that if the query parameters are set, it will use them in the sql statement and if not, it will just return all the rows.
Below is the displayListings function which is called every time the page is loaded.
Although I'm showing the whole function, I havent implemented most of it because nothing works past the line where I use $_GET.
<?php
function displayListings() {
global $dbConnection;
//checks if the query parameters exist
if (isset($_GET['title'])) {
echo 'got here... :F';//for debugging
var_dump($_GET['title']);//for debugging
$title_filter = $_GET('title');// THIS IS THE LINE THAT THE SCRIPT STOPS AT
var_dump($title_filter);//for debugging
}
//checks if the query parameters exist
if (isset($_GET['artist'])) {
$artist_filter = $_GET('artist');
echo $artist_filter."/n";
}
//checks if the query parameters exist
if (isset($_GET['release'])) {
$release_filter = $_GET('release');
echo $release_filter."/n";
}
echo 'here!';
// connect to the database
if (!connectToDb('musiconline')) {
$_SESSION['errorMsg'] = "Sorry, we could not connect to the database.";
header('location:listItem.php');
exit();
}
// after this point we have an open DB connection
// gets the current highest ID so we know what the next should be.
$sqlQuery = "SELECT listingid, recordtitle, artist FROM vinyl";
$result = $dbConnection->query($sqlQuery);
if (!$result) {
$_SESSION['errorMsg'] = "There was a problem with the database: " . $dbConnection->error;
closeConnection();
header('location:listItem.php');
exit();
}
//gets the results and puts them in a rows array
while($row = $result->fetch_array()){
$rows[] = $row;
}
//iterates through each row of the results (each vinyl)
foreach($rows as $row){
$listingID = $row['listingid'];
$recordTitle = $row['recordtitle'];
$artist = $row['artist'];
echo '
<div class="listing">
<table class="tableception">
<tr><td><img src="uploads/vinyl'.$listingID.'.png" alt="img1" ></td><td>
<table class="listing-table">
<tr><td>Album title: </td><td>'.$recordTitle.'</td></tr>
<tr><td>Artist name: </td><td>'.$artist.'</td></tr>
</table>
</td></tr>
</table>
</div>
' . "\n";
}//END OF FOREACH
/* free result set */
$result->close();
/* close connection */
closeConnection();
}
?>
When I debug the page in my IDE, everything works fine, probably because there are no query parameters in the URL.
The page stops loading after the $_GET line, as seen below.shows screenshot of browser when query parameters exist in URL.
I just cant figure out what I'm doing wrong.
Thanks in advance.
I used curly brackets instead of square brackets in the line.
I had $title_filter = $_GET('title');
instead of $title_filter = $_GET['title'];
Thanks #AymDev for pointing this out to me!

Adding hyperlink to a table element, carrying its informations [PHP]

Being a huge PHP newbie I find myself stuck here.
I have an HTML table for a videogame store filled with elements taken from my database.
The point is, I want to be able to add a link to the game title. Moreover I want the link to direct to some "gamePage.php", a php page used for every videogame but of course showing different infos for each game (title, console etc).
The fact is that not only I can't add the hyperlink, but I have no clue on how to carry the videogame infos when I click on a link (even managing to add the link, all I would manage to do would be redirecting the user to a blank gamePage.php with no title).
This is the code I use to fill the table (the restore function fills my table):
<html>
<body>
<div>
<table width = "550px" height = "300px" border="2" >
<tr bgcolor="#5f9ea0">
<td>Title</td>
<td>Console</td>
<td>Genre</td>
<td>Price</td>
</tr>
<?php
$conn = #pg_connect('dbname=project user=memyself password=project');
function search(){
<!-- Work in progress -->
}
function restore(){
$query = "SELECT v.Title , c.Consolename , g.Genrename , v.Price
FROM vg_shop.videogame v, vg_shop.console c, vg_shop.genre g
WHERE v.Console=c.IDConsole AND v.Genre=g.IDGenre";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
}
}
<!-- some code -->
</body>
</html>
At first i tried to do this
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
$myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
But all I get is a white page, there's some syntax error I don't get.
And, even if it worked, I still can't carry at least the videogame PID through the gamePage link
so, you're managing to go to gamepage.php somehow.
So you need to add some sort of identifier to your link you that you could do some query on the gamepage.php by using that identifier to get info for that particular game.
while($myrow = pg_fetch_assoc($result)) {
printf ("<tr><td><a href='gamePage.php?id=%s'>%s</a></td><td>%s</td><td>%s</td><td>%s</td></tr>", $myrow['id'], $myrow['title'], $myrow['consolename'], $myrow['genrename'], $myrow['price']);
Note: I assume that you're picking $myrow['id'] from database as well.
now on your gamepage.php do following.
$id = $_GET['id'];
$sql = "SELECT * FROM vg_shop.videogame WHERE `id` = $id";
$result = pg_query($sql);
if($result){
$result = pg_fetch_assoc($result):
//...
// echo "Name: ".$result['Title'];
// other fields
}
$result will have all info about that particular game that was clicked, you can display all as you want.
Cheers :)

update checkboxes after submit

I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)

PHP mysql not showing up admin panel feature

so i've been up for a long time working on this. So basically want I need to do is make an add, update, delete user table. Right now i'm currently just working on a table that shows what I have in my database and options to edite, delete, or add.
I have 2 tables in my database.
Links Table with the fields of : PID, LinkName, AnchorText, CategoryID, CategoryName
linkCategory table with the fields of : CategoryID, CategoryName
here's what I have so far.... and it's not showing up at all. No errors or anything.
<?php
// acquire shared info from other files
include("dbconn.inc.php"); // database connection
include("shared.php"); // stored shared contents
// make database connection
$conn = dbConnect();
print $HTMLHeader;
print $PageTitle;
?>
<script>
function confirmDel(title, pid) {
// javascript function to ask for deletion confirmation
url = "admin_delete.php?pid="+pid;
var agree = confirm("Delete this item: <" + title + "> ? ");
if (agree) {
// redirect to the deletion script
location.href = url;
}
else {
// do nothing
return;
}
}
</script>
<?php
// Retrieve the product & category info
$sql = "SELECT Links.PID, Links.AnchorText, linkCategory.CategoryName FROM Links, linkCategory where Links.CategoryID = linkCategory.CategoryID order by linkCategory.CategoryName";
$stmt = $conn->stmt_init();
if ($stmt->prepare($sql)){
$stmt->execute();
$stmt->bind_result($PID, $Title, $CategoryName);
$tblRows = "";
while($stmt->fetch()){
$Title_js = htmlspecialchars($Title, ENT_QUOTES); // convert quotation marks in the product title to html entity code. This way, the quotation marks won't cause trouble in the javascript function call ( href='javascript:confirmDel ...' ) below.
$tblRows = $tblRows."<tr><td>$Title</td>
<td>$CategoryName</td>
<td><a href='admin_form.php?pid=$PID'>Edit</a> | <a href='javascript:confirmDel(\"$Title_js\",$PID)'>Delete</a> </td></tr>";
}
$output = "<table border=1 cellpadding=4>\n
<tr><th>Title</th><th>Category</th><th>Options</th></tr>\n".$tblRows.
"</table>";
$stmt->close();
} else {
$output = "Query to retrieve product information failed.";
}
$conn->close();
?>
<?= $SubTitle_Admin ?>
<br>
| Add a new item |<br>
<?php echo $output ?>
<?php print $PageFooter; ?>
</body>
</html>
This is my first page, I still have to put in the PHP for edit, update, and delete... but can't even get my main page to show up. A bit lengthy, but I need to get this done. If anyone could help me out, or point me the right direction... I would be grateful. Here is a link to what it should look like http://omega.uta.edu/~cyjang/ctec4321/lab/productList2/admin_productList.php. When I try to pull my own up it's a blank page... like this: http://omega.uta.edu/~dxh6110/4321/in%20class/linksadmin/admin_productList.php

How do i display specific results from SQL database in a HTML TABLE using select menus

I've been at this for hours and i have gotten a slight break through, however i am at a stand still at the moment. I have a SQL Database that store vehicle information, such as make, model and year. What i want to do is allow users to modify the query and only display specific results.
I understand how to display all the records at once but what i want to add is when the user selects say for example the make as "Toyota" i want only that specific make to appear. I did reach some where in this, by using this code:
<form method="post" action="">
<div id="search_query" >
Make
<select name="make" size="0">
<option value="honda">Honda</option>
<option value="toyota">Toyota</option>
<option value="nissan">Nissan</option>
</select>
<input type="submit" name="submit" value="submit">
</div>
</form>
<?php
$db_con = mysql_connect('localhost', 'root', '');
if (!$db_con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my_db', $db_con);
$make = mysql_real_escape_string($_POST['make']);
$sql = sprintf("SELECT * FROM chjadb_vehicles WHERE v_make= '$make' ");
$result = mysql_query($sql);
echo "<table width= 970 border=1>
<tr>
<th width='120' scope='col'>Image</th>
<th width='170' scope='col'>Details</th>
<th width='185' scope='col'>Seller</th>
<th width='126' scope='col'>Price</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td> <img src=" .$row['v_image']. " width =200 height = 130>" . "</td>";
echo "<td>". $row['v_year'] . " " . $row['v_make'] . " ". $row['v_model'] . " ". $row['b_type']. "</td>";
echo "<td>". $row['user_id'] ."</td>";
echo "<td>". $row['v_price'] ."</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($db_con);
?>
however when i run the page initially i get this error: "Notice: Undefined index: make in C:\xampp\htdocs\carhuntja.com\buy_a_car.php on line 62"
i did some research and realized that this was happening because i had no make value set, what i wish to do here is at the start of going to that page i want all vehicles to be displayed.
The problem is that the query is being sent before the user chooses a make. To fix this, you need check that the user has actually submitted the form by enveloping your PHP code in if(isset($_POST['submit'])) ("submit" is used because that is the name of your submit button).
//place connection code here (do not query the database yet)
if(isset($_POST['submit']))
{
//all of the database retrieval code
}
else
{
$query_makes = "SELECT v_make FROM chjadb_vehicles";
$result_makes = mysqli_query($query_makes);
echo "Please choose a make."
//echo opening select tag
while($row = mysql_fetch_array($result_makes))
{
//echo each option tag
}
//echo ending select tag
}
Also, you are missing a slash in the self-contained input tag.
Finally, you should use MySQLi functions because MySQL functions are deprecated in PHP.
When the page loads for the first time you need to run this query:
SELECT * FROM chjadb_vehicles
You need to check if the user clicked the submit button and posted the make field, to do that use isset():
if (isset($_POST['make']){
$make = mysql_real_escape_string($_POST['make']);
}
I strongly suggest you use jquery and ajax
EDIT:
First time the page loads you display all vehicles.
In your javascript you bind a onSelect evvent to the dropdown and once the user selects a make, you send an ajax request to the server and display the new results from the server, so it'll look something like that:
$('#search_query select').change(function(){
//get the selected option text
var selectedVal = $(this).find('option:selected').text();
//send ajax request
$.ajax( {
url : url,
type : "POST",
data : selectedVal ,
dataType : 'json',
success : function(data) {//handle returned data}
})
});
I suggest you take a look here, for a complete VIDEO tutorial on jquery.

Categories