Sorry, I'm not sure how to really word my question. Here it goes.
If you go to my page http://www.eveo.org/stack/view.php you will notice on the right hand side there are links that read "restore" and "delete". If it says restore, the value for the "deleted" table in the database is "y".
The problem: When I click on a link, all of them change, not just the one. What I need to do is when I click on "delete" or "restore" on any of them, only that row will delete and restore and only will that rows link update, with all the others staying the same. The value in the database has to change from "y" to "n" or vice versa depending on the link.
The code that currently changes my link for all of them is:
echo "<td><a href='view.php?'>";
$y="$row[deleted]";
$x="$row[id]";
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
I've been trying to solve this for hours, and it's not working.
Requirements: It has to use URL rewriting, so I can't do this change thing with javascript or something, personally I would have, but these are my professors requirements.
Source code:
VIEW.PHP
<?php { ?>
<table border="0" cellpadding="0" cellspacing="0" id="table">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>MANUFACTURER</th>
<th>MODEL</th>
<th>DESCRIPTION</th>
<th>ON HAND</th>
<th>REORDER</th>
<th>COST</th>
<th>PRICE</th>
<th>SALE</th>
<th>DISCOUNT</th>
<th>DELETE</th>
</tr>
</thead>
<tbody>
<?php } ?>
<?php
// while($r = mysql_fetch_array($resultDeleted))
// {
// echo $r[0];
// }
?>
<?php while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
$y=$row[deleted];
$x=$row[id];
if ($y == 'n'){
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$row[id]'");
echo "delete";
}
else if ($y == 'y'){
mysql_query("UPDATE inventory SET deleted = 'n' WHERE id='$row[id]'");
echo "restore";
}
echo"</a></td>";
echo "</tr>";
} ?>
<?php { ?>
</tbody>
</table>
<?php } ?>
It looks like you are trying to get a $_GET variable using the code:
$y="$row[deleted]";
$x="$row[id]";
This is never going to work. First of all you don't need to add double quotes around your variables. Second the correct syntax for getting the $_GET variables is:
$delete = $_GET['delete'];
$id = $_GET['id'];
As you can see I have given your variable names better descriptive names.
Second, when you are just adding those variables to a query you will have a huge SQL injection hole in your application:
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
What if I was a hacker I would add an id of: 1' or 1=1, which would result in the following query:
UPDATE inventory SET deleted = 'y' WHERE id='1' OR 1=1
And suddenly I set the deleted status of all records in the table. I could even get into others tables using this attack in do whatever I want.
So you should always use mysql_real_escape_string():
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = 'y' WHERE id='$id'");
So what you will get is the following:
$delete = mysql_real_escape_string($_GET['delete']);
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE inventory SET deleted = '$delete' WHERE id='$id'");
Another thing is that you don't need to keep opening and closing the PHP tags. Only if you want to add some HTML.
Next:
instead of echoing all that stuff simply use HEREDOC:
So instead of doing:
echo "<tr>";
echo "<td>$row[id]</td>";
echo "<td>$row[name]</td>";
echo "<td>$row[manufac]</td>";
echo "<td>$row[model]</td>";
echo "<td>$row[descrip]</td>";
echo "<td>$row[onhand]</td>";
echo "<td>$row[reorder]</td>";
echo "<td>$row[cost]</td>";
echo "<td>$row[price]</td>";
echo "<td>$row[sale]</td>";
echo "<td>$row[discont]</td>";
echo "<td><a href='view.php?'>";
You can simply do:
echo <<<HTML
<tr>
<td>{$row['id']}</td>
<td>{$row['name']}</td>
etc
FOOBAR;
As you can see it need quotes to get an array element.
After that you should build your links:
$delete = 'n';
if ($row['deleted'] == 'n') {
$delete = 'y';
}
echo 'delete';
As a general note:
ALWAYS ENABLE FULL ERROR REPORTING ON DEV ENVIRONMENT so you can see what the f*&k is going on / wrong. So place this at the top of your scripts:
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
What you want will not work like that. Your code changes your database entries upon each refresh. To illustrate, if you will keep refreshing your page, the links will change from deleted to restored and vice versa indefinitely.
What you need to do is take those two update clausules out of the loop, give each link an id. Something along the lines of
if ($y == 'n'){
echo "<a href='view.php?link_id=$row[id]&case=delete'>delete</a>";
}
else if ($y == 'y'){
echo "<a href='view.php?link_id=$row[id]&case=restore'>restore</a>";
}
Then somewhere above the loop you would to the actual update.
if(!empty($_GET['link_id'])) {
if($_GET['case'] == 'restore') {
// udpate
} else {
// update
}
}
The other way would be to use a form for this. Then you would just catch the post request and do the same thing.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// do stuff
}
or
if(!empty($_POST)) {
// do stuff
}
You need to pass the id to the query, maybe something like this:
<?php while($row = mysql_fetch_array($result)) {
if($row['deleted']=='y'){$status='restore';}else{$status='delete';}
echo "<tr>";
echo "<td>{$row['id']}</td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['manufac']}</td>";
...
echo "<td><a href='view.php?id={$row['id']}&do=$status'>".ucfirst($status)."</a></td>";
echo "</tr>";
?>
Then have the script receive a request to alter the values, something like this would go at the top of your script:
<?php
if(isset($_GET['id']) && is_numeric($_GET['id']) && isset($_GET['do'])){
$set=null;
$id=(int)$_GET['id'];
if($_GET['do']=='delete'){$set='n';}
if($_GET['do']=='restore'){$set='y';}
if($set != null){
mysql_query("UPDATE inventory SET deleted = '$set' WHERE id='$id'");
}
}
?>
Related
So I have been working on this code for a while. I believe I am really close. My if statement that is inside my while loop isn't showing any data in the area it's suppose to show. I know mysql is old and deprecated. I am going to change it once I figure this out.
$result = mysql_query("SELECT * FROM inventoryTable",$db);
$result2 = mysql_query("SELECT * FROM users WHERE username='$username' and sub = 'yes'",$db);
echo "<TABLE style=\"background-color: #FFFFFF; border: 10px solid A4A4A4;\">";
echo"<TR><TD>"."<B>Title</B>"."</td>";
echo"<TD>"."<B>Authors First Name</B>"."</td>";
echo"<TD>"."<B>Authors Last Name</B>"."</td>";
echo"<TD>"."<B>ISBN</B>"."</td>";
echo"<TD>"."<B>Publisher</B>"."</td>";
echo"<TD>"."<B>Course Number</B>"."</td>";
echo"<TD>"."<B>Source</B>"."</td></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
?>
This is the part of my code that isn't showing any results.
while
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["title"]."</td>";
echo "<TD>".$myrow["authorsFirst"]."</td>";
echo"<TD>".$myrow["authorsLast"]."</td>";
echo "<TD>".$myrow["ISBN"]."</td>";
echo "<TD>".$myrow["publisher"]."</td>";
echo "<TD>".$myrow["courseNum"]."</td>";
while ($subResults = mysql_fetch_row($result2))
{
If($subResults == 'yes' )
{
echo "<td>".$myrow["source"]."</td>";
} else {
echo "<TD>"."Please subscribe to View"."</td>";
}
echo "</TABLE>";
}
}
I want my session user to be able to see the source from my inventory table if they have a yes in the sub field. If they do not have a yes in the sub field, they will see please subscribe to view. Am i doing the mysql_fetch incorrectly or is there a problem because I have 2 while loops going on at once.
you need to have "==" to compare two values, otherwise you assign the second value to the first variable:
...If($username == $subResults)...
or to use a strict comparison of type and content, use "==="
If($username === $subResults)
also I am thinking the code should be
...If($subResults ==="yes"){echo"....///desired content";}else{echo"...//alternate content";}...
and you are missing the echo statement and closing </td> in the code
"<td>".$myrow["source"];
should be
echo"<td>".$myrow["source"]."</td>";
in fact - aren't you missing the closing td's in all of the cells?
I want to make a link to delete a record from database using dynamic links with php however i couldn't figure it out
this is my code :
<?php
$query = "SELECT * FROM posts ";
$result = mysqli_query($connect, $query);
?>
<table>
<tr style="background: #afafaf;">
<th>Id</th>
<th>Title</th>
<th>Action</th>
</tr>
<?php
while($rows = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td class=\"center\">".$rows['id']."</td>";
echo "<td>".$rows['title']."</td>";
echo "<td> delete</td>";
echo "</tr>";
}
?>
</table>
the output link would be like .../delete.php?id=X
can anyone help me write the code for delete.php ?
Have the below code in your page. This first checks if $_GET['id'] is set. It will only run if it is, that way you don't get Undefined Index error.
<?php
if (isset($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
I also used htmlspecialchars to sanitize the user input. You could run some validation using ctype_digit to ensure that the input is actually an integer.
I suggest using prepared statement in MySQLi to prevent SQL injection.
Edit 1
Example with ctype_digit. This checks if the id is set and if it is a number, technically you could just use ctype_digit because if id is empty then ctype will return false as var_dump(ctype_digit("")); will return false, with that logic in mind, the value must be set for ctype_digit to work and it must be an integer.
<?php
if (ctype_digit($_GET['id'])) {
$deleteId = htmlspecialchars($_GET['id'], ENT_QUOTES);
$delete = "DELETE FROM `posts` WHERE `id` = " . $deleteId;
}
?>
That would be something like this:
$deleteId = $_GET['id'];
$sql = "DELETE FROM posts WHERE id = ".$deleteId;
Remember to escape your variables before sending them off to the MySQL server.
I'm new to PHP and I'm trying to build a small customer database.
In my database, I have a column named "suspended_state" and the value can be either 'yes' or 'no' and if it's yes, I'd like it to show Suspended, if it's no I'd like it to display Active.
Here's my code:
<?php
$result = mysqli_query($con,"SELECT suspend_state FROM tbl_company WHERE company_id='$company_id'");
while($row = mysqli_fetch_array($result));
if ($row['yes'])
echo "Suspended";
else {
echo "Active";
}
?>
However, all results come back as Active regardless of weather the column is 'yes' or 'no'
Please could someone point out where I'm going wrong?
You aren't selecting a column named 'yes'... and remove the ; as mentioned by Fred and add curly brackets as mentioned by BigScar try
while($row = mysqli_fetch_array($result)) {
if ($row['suspend_state'] == "yes") {
echo "Suspended";
} else {
echo "Active";
}
}
I seem to be stuck on a concept in database query and website development.
I have a website that will reflect what data is stored in a database and the website needs to change depending on that data: therefore, my menu system will not be hardcoded in. It builds my menu system based off a query of all the models in my database. The action of clicking on the menu will show tables without changing the page (a simple javascript "showtables" function). like so:
function showTables(TABLE_NAME)
{
if(TABLE_NAME != "PRINTER_TABLE")
{
document.getElementById("PRINTER_TABLE").style.display ="none";
}
if(TABLE_NAME != "show_ALL_PRINTERS")
{
document.getElementById("show_ALL_PRINTERS").style.display ="none";
}
document.getElementById(TABLE_NAME).style.display ="block";
}
I did not include all of my other if statements because there are about 15 of them. These statements will hide everything and the only show the formatted table of "TABLE_NAME" at the end of that script.
My problem is that, if all of the data will not be hardcoded in either HTML or PHP, I need to pass into my function "showTables" a model type or ID that will come from my query.
My Menu system code snipet:
<li class="hasmore"><span>Printer Parts</span>
<ul class="dropdown">
<?php
include 'connection.php';
$query = "SELECT * FROM all_printers";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
#echo "<h3>" . $row['printer_model'] . "</h3>";
echo "<li>" .$row['printer_model']."</li>\n";
}
?>
This puts the model into the menu system and the "PRINTER_TABLE" will access my showTables function, which then will show that table. But there are many different printer models and I need to tell my table query what specific model to get info on.
I hope this makes sense as there is a lot of logic behind it. Maybe there is an easier way..?
In my tables I have:
<table id="table">
<thead>
<tr>
<th scope="col" id="table">Type</th>
<th scope="col" id="table">Size</th>
<th scope="col" id="table">S/N</th>
<th scope="col" id="table">Model</th>
<th scope="col" id="table">Connection Type</th>
<th scope="col" id="table">Surplus</th>
<th scope="col" id="table">Amount</th>
</tr>
</thead>
<tbody>
<?php
include 'connection.php';
$query_misc = "SELECT * FROM all_parts WHERE part_type='MISC'";
$result_misc = mysql_query($query_misc);
while($row = mysql_fetch_array($result_misc))
{
echo "<tr>";
echo "<td><div align=\"center\">".$row['part_type']."</div></td>";
echo "<td><div align=\"center\">".$row['part_size']."</div></td>";
echo "<td><div align=\"center\">".$row['part_sn']."</div></td>";
echo "<td><div align=\"center\">".$row['part_model']."</div></td>";
echo "<td><div align=\"center\">".$row['part_connection']."</div></td>";
echo "<td><div align=\"center\">".$row['part_surplus']."</div></td>";
echo "<td><div align=\"center\">".$row['part_temp_amount']."/".$row['part_amount']."</div></td>";
echo "</tr>";
}
..... etc
Any ideas?
EDIT:
I do now know how to put what I click on, into the url properly..
<?
$query = 'SELECT printer_id, printer_model FROM printer_table WHERE 1 ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
{
echo "<li>" .$product['printer_model']."</li>\n";
}
?>
or
<li><?=$product['printer_model']?></li>
doesnt work properly, because i need to call the suggested part list php part, but do not know where to do so..
EDIT:
I placed that php within a div and the echos will fill out my table, but how am I suppose to call that div to only run when that onclick action? I know that is not how divs work, It would seem I would need a JS function but I know you cannot do php within JS. AJAX perhaps?
EDIT----------------------------------------------------
The call here to the DB is correct, tested it manually without any errors, but I am still receiving a syntax error upon loading my home page. Here is my call to the DB via PHP...
<?
if (!isset($_GET['action']))
{
//If not isset -> set with dumy value
$_GET['action'] = "undefine";
}
include 'connection.php';
$query = 'SELECT ppart_table.* FROM ppart_table LEFT JOIN printer_part_relation ON ppart_table.part_id = printer_part_relation.part_id WHERE printer_part_relation.printer_id ='.mysql_real_escape_string($_GET['printer_id']);
$parts = mysql_query($query) or die("Query failed with error: ".mysql_error());
while ($row = mysql_fetch_assoc($parts))
{
echo table blah blah
}
?>
I have tried supressing all errors via this:
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
And the syntax error at page load still exist.
My home page of this site does NOT have the "product_id=" after mysite.php
I would recommend using PHP's PDO class for database access. I would also recommend using JQuery for all of you javascripting. It makes things VERY simple. It would also be advantagious to keep your display code away from your business logic (two languages should for the most part not be in the same source file ie: HTML/PHP/Javascript). I will stick with what is familiar for now however. perhaps something like this?
menu
<ul>
<?
$query = 'SELECT id, name FROM product_category_table WHERE 1 ORDER BY name';
$product_categories = mysql_query($query);
while ($product_category = mysql_fetch_assoc($product_categories)) :
?>
<li>
$product_category['name']
<ul id="<?= $product_category['id'] ?>" style="display: none;">
<?
$query = 'SELECT id, name FROM product_table WHERE category_id = ' . $product_category['id'] . ' ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
?>
<li><?= $product['name'] ?></li>
<?
endwhile;
?>
</ul>
</li>
<?
endwhile;
?>
</ul>
javascript
function toggleVisibility(category) {
var element = document.getElementById(category);
if (element.style.display == 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
part list
<?
$query = 'SELECT part_table.* FROM part_table LEFT JOIN product_to_part_associations_table ON parts_table.id = product_to_part_associations_table.part_id WHERE product_to_part_associations_table.product_id = ' . mysql_real_escape_string($_GET['product_id']);
$parts = mysql_query($query);
while ($part = mysql_fetch_assoc($parts)) {
echo part table blah blah
}
?>
db tables
product_category_table
id, name, etc
product_table
id, category_id, name, etc
part_table
id, name, etc
part_to_product_association_table
id, product_id, part_id
set the proper indexes on your table columns for speed. the part_to_product_association table allows for a many to many relationship between records in the product table and records in the parts table (needed in the case one part could be used in multiple products, and one product can use multiple parts).
I have a code that I have used over and over again before and now it's messing up. All I want to do is list information from the database into the table on the page, but now it will only show one result, instead of all the results it has found.
<table>
<tr><td style="background-color:#009745; color:#FFFFFF"><center><strong>Address Book</strong></center></td></tr>
<tr>
<?php
$getids = mysql_query("SELECT id, first_name, last_name FROM accounts WHERE s1='$id' ORDER BY id DESC", $db);
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
?>
<td><?= $ab_id ?> - <?= $ab_fn . " " . $ab_ln ?></td>
<?php
} else {
?>
<td><center>No Contacts</center></td>
<?php
}
?>
</tr>
</table>
please help me with this.
Thank You for your help :)
I love this site!! I can always get answers when I need them.
I saw two thing wrong
you are using mysql_fetch_array and later you are using string indexes to print the result
print the things in loop it is overriding values and just storing last row
if (mysql_num_rows($getids) > 0) {
while ($gids = mysql_fetch_assoc($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
echo '<td>'.$ab_id.' -'. $ab_fn.''.$ab_ln.' </td>';
}
In this messy code you're closing the while loop too early:
while ($gids = mysql_fetch_array($getids)) {
$ab_id = $gids['id'];
$ab_fn = $gids['first_name'];
$ab_ln = $gids['last_name'];
}
Only the last retrieved row is used later on. Also, don't use mysql_fetch_array if you're not accessing the numeric indeces of your result. Use mysql_fetch_assoc instead.