I'm still new to php and working my way around it but i'm stuck at the following piece:
code for deleting a row in my table
i have a link directing towards this piece of my script. i run through the first half just fine but when i press on submit and try to execute my delete query it won't go to my second if statement let alone get to the delete query.
$pgd is the page id
my hunch is there is problem with the action in the form i'm building after my while statement
forgive me for the wierd formatting of my msg but its 2am and very tired, i promise to format my questions in the future better! any help is appreciated
edit: ok other then the obvious mistake of missing method=post #.#;
edit:
hey everyone,
first of all, i'd like to thank everyone for their response.
i just started coding in php last weekend so forgive my messy codes. the code is still running locally and my main goal was to finish the functions and then work on securing my code.
now back to the issue, i'm sorry if i was vague about my problem. i'll try to reiterate it.
my issue isn´t selecting an item i want to delete, the issue is that it won´t get to the 2nd if statement.
Re-edit:
this time with my current code:
if($_GET['delete'] == "y")
{
//content hier verwijderen
$sqlcont1="SELECT * FROM content where id ='".$_GET['id']."'";
echo $sqlcont1;
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while($rowcont1= mysql_fetch_array($resultcont1)){
echo '<form class="niceforms" action="?pg='.$pgd.'&delete=y&remove=y&id='.$_GET['id'].'" method="post">';
echo '<h1>'.$rowcont1['Titel'].'</h1>';
echo '<p>'.$rowcont1['Content'].'</p>';
echo '<input type="submit" value="Delete article">';
echo '</form>';
}
if($_GET['remove']=="y"){
echo 'rararara';
$id=$_GET['id'];
$sqlrem="DELETE FROM content WHERE id="$id;
echo $sqlrem;
mysql_query($sqlrem);
}
}
echoing $sqlrem gives me the following now:
DELETE FROM content WHERE id=8
that being my current code, i get in to the second IF statement but now to get it to delete!
#everyone:
ok maybe thinking out loud or following my steps worked but the code works, i know its very messy and it needs fine tuning. i'd like to thank everyone for their help and feedback. i'm liking this and you'll probably see me alot more often with nubby questions and messy codes with no escapes :(
First of all, you have SQL injection vulnerability in your script. Anyone can add some string that will be attached to your query, possibly altering it in a way that can make almost anything with the data from your database.
Escape your values with one of anti-SQL-injection methods. Read more for example on php.net/manual/en/function.mysql-query.php
To the point...
Your deletion code will be executed only if you invoke URL with two params (remove and delete set to y. That means your URL should look similar to something.php?delete=y&remove=y. Maybe you just did not spot it.
Please give details about any errors that occured and tell me whether the above mentioned solution helped.
mysql_fetch_array() returns an array
your while statement acts as an if, and does not iterate thru the array returned as you think it does
you need something like
$all_rows = mysql_fetch_array($result);
foreach ($all_rows as $row) {
$sql = "delete from table where id = " . $row['id'];
}
It looks to me like you're mixing two forms together here: you're wanting to see if you went to the delete row form (the first few lines), and you're trying to present the delete row form (the while loop.) I would break these two things apart. Have a page that simply displays your forms for row deletes, and another page that processes those requests. And another page that brings you to the delete rows page.
For now, just echo all the values you're expecting to receive in $_GET[] and see if they are what you expect them to be.
You have a lot of problems in that script alone, so just to make things easier (considering you uploaded a pic), put an
echo $sqlrem;
in your second if statement, see if the query is displayed. If not, it means it doesn't even get to that part of code, if it gets displayed, copy it and run it in phpmyadmin. That should output a more coherent error message. Tell us what that is and we'll work it through.
I also noticed that your DELETE SQL query might have an issue. If your $pgd' id is a integer, you shouldn't include the ' single quote, that is for string only.
**Correction**
$sqlrem = "DELETE FROM content WHERE id = " . controw1['id'];
EDIT
Anyway, just to help out everyone, I typed out his code for easier viewing.
I think his error is $rowcont1['Tilel'] --> that might caused PHP to have an error because that column doesn't exist. I assumed, it should be `Title' causing an typo error.
if(_$GET['delete'] == "y") {
$sqlcont1 = "SELECT * FROM content where id ='" . $_GET['id'] . "'";
$resultcont1 = mysql_query($sqlcont1) or die (include 'oops.php');
while ($rowcont1 = mysql_fetch_array($resultcont1)) {
echo '<form class = "niceforms" action = "?pg=' .$pgd . '&delete=y&remove=y">';
echo '<h1>' . $rowcont1['Title'] . '<h1>'; // <-- error here
echo '<p>' . $rowcont1['Content'] . '</p>';
echo '<input type = "submit" value = "Delete article">';
echo '</form>';
}
if ($_GET['remove'] == "y"){
$sqlrem = "DELETE FROM content WHERE id = " . $rowcont1['id'];
mysql_query ($sqlrem);
}
}
Related
i tried to find a solution for my problem for 2 hours now, but i don't know why my code does not work.
I have a sql output which looks like this:
function output(){
while($row = $this->statement->fetch()) {
$id = $row["id"];
echo '
<tr>
<td>'.$row["comname"].'</td>
<td>'.$row["district"].'</td>
<td>'.$row["industry"].'</td>
<td>"Details"</td>
</tr>
<br>
';
}
If someone click on the link "Details" i want to give out more information about that specific company. Therefore i save the id in the url to identify which company was clicked.
To check if the Details link was clicked, i wrote this:
Edit: just added the "$id = $_GET['details']" after your hints, it looks like this now:
if (isset($_GET['details'])){
$id = $_GET['details'];
echo $id;
}
}
When i click on the link "Details" it changes the URL correctly, but it doesn't print the id. (I don't only want to print the id, i just do this to check the functionality.) Why does my code not work? Is there a second "$GET" i have to use? I really don't know what is going on.
Edit: The php-code ends here, there is nothing i do afterwards.
Edit2: I tried print_r($_GET) and it looks like, the id is not even in the $GET-Array. Also the if (isset($_GET['details'])) statement is not executed.
Thank you!
You should print the $_GET['details']:
if (isset($_GET['details'])){
echo $_GET['details'];
}
Or put it in a variable:
if (isset($_GET['details'])){
$id = $_GET['details'];
echo $id;
}
$_GET[] is just an array of all GET parameters in the URL. You see them for example on https://www.google.com?q=stack+overflow where the parameter q is set to stack+overflow. So if you would echo out $_GET["q"] on that URL you would get stack+overflow. You can store it in a variable like $id and echo it out, but you need to set it first like $id = $_GET["details"];
EDIT: I just realized the code you have now is vulnerable to an attack called XSS or HTML Injection. Since we can specify the $_GET["details"] and so $id that is being echoed, an attacker can put HTML code or the <script> tag in there to execute dangerous JavaScript code on everyone that accesses the URL.
Luckily, there is an easy fix: just put the function htmlspecialchars() around whatever user input you echo. The echo you have here would become echo htmlspecialchars($id);
I have a form that up to yesterday was working with post to insert the form data into mysql table. Today it all stopped working and I changed nothing. This is driving me crazy.
Allot of the answers provided on line are based on correcting incorrect code. My code is correct, at least i think it is. It all worked fine after I wrote it and used it for several days. Then one day it just stopped working.
My post code is as follows.
<?php
include 'quality_module_connect.php';
// Don't forget to properly escape your values before you send them to DB
// to prevent SQL injection attacks
echo "<p>Content variables $_POST is:</p>";
print_r($_POST);
$field1 = $mysqli_real_escape_string($_POST['field1']);
$sql = "INSERT INTO test(test)
VALUES ('$field1')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
The results are that nothing is getting posted into the mysql table and I get no error message. When I insert with an insert statement without using post it all works fine.
How do I solve the problem?
I found the answer and it was not in the code, at least I do not think it was. I was opening the form using a hypelink with target="_blank"in the hyperlink statment so that it would open on a new tab. For some reason the new tab requirements with target="_blank" was causing the POST to be empty. Once I got rid of that everything is back to normal and fine. It would be nice to understand why.
i found many answers about that problem but nothing solved my problem - so i want to show you my code and hope that someone can find the mistake..
I have a standard HTML formular that gives some data with POST to the next .php file where i get it and save it into session-variables. I use the session variables about 2 reasons:
if someone reloads the page, it should show the same information as before.
I need the variables in upcoming php files.
Here is the code:
session_start();
// Handle Variables on post and reloaded-page
if(isset($_POST["locId"]) && isset($_POST["dateId"]) )
{
$locId = htmlspecialchars($_POST["locId"]);
$dateId = htmlspecialchars($_POST["dateId"]);
$_SESSION["locId"] = $locId;
$_SESSION["dateId"] = $dateId;
echo "Session variables are set: locId = " . $_SESSION["locId"] . " dateId = " . $_SESSION["dateId"];
} elseif(isset($_SESSION["locId"]) && isset($_SESSION["dateId"])) {
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
} else {
$load_error = 1;
$status = "alert alert-danger";
$message = "shit, no variables here";
}
The frist call works fine - session variables are set and the echo gives the right values. After reloading the page i get the echo "get it from session" but my variables have no values.
i also checked my session_id() on first call and reload.. they are NOT the same.
I testet a simple test.php file where i start a session with a variable and ask for the variable in the next file. It works fine :-/
Its just a problem with my code above. I think my webserver is handling right. But what reasons are there for chaging a session id and losing session-variable values?
Damn! To write correct is everything ...
I found my mistake.
Look at the code in my question. The second session-variable is $_SESSIOn["dateId"].. the n is lowercase! If i write it correctly and complete in UPPERCASE it is working.
Also the session_id is not chaging anymore and i can output the session_id() as much as is want.. but one mistake in $_SESSIOn changes everything. New session_id on every call, ... strange.
Learned something again :-) Thanks to everybody for the answers and your time! I hope i can help you in the future
Well, your mistake is quite easy to find. In fact, your code works perfectly. But look at this part:
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
Well, you asign the session values to two variables, but in fact, you simply missed to output them anywhere. Thats why you get "get it from session" but then is displays nothing, you need to echo them.
Simply add an echo and it will display your vars perfectly :)
echo "get it from session";
$locId = $_SESSION["locId"];
$dateId = $_SESSIOn["dateId"];
echo $locId;
echo $dateId;
Try this:
session_id();
session_start();
I have two PHP pages. On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
Right now this has been my approach:
This is (part) of the code on page1:
ob_start();
session_start();
//Select data from temporary table
$result = mysqli_query($mysqli,"SELECT * FROM table");
//store table into session variable
$_SESSION['fase1result'] = $result;
This is the code on page2:
ob_start();
session_start();
$table = $_SESSION['fase1result'];
echo "<table border='1'>
<tr>
<th>ProductID</th>
<th>ProductName</th>
<th>Fase1</th>
</tr>";
while($row = mysqli_fetch_array($table))
{
echo "<tr>";
echo "<td>" . $row['ProductID'] . "</td>";
echo "<td>" . $row['ProductName'] . "</td>";
echo "<td>" . $row['Fase1'] . "</td>";
echo "</tr>";
}
echo "</table>";
Unfortunately, up until now these scripts return me an error on page2. At this moment, the echoing of the table on page2 is just to test and verify that the table is actually passed on. At a later moment I want to be able to use MySQL queries to further add data to the table. Hope you could help me.
UPDATE:
Error that I'm getting is:
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in domain/page2.php on line 32
With line 32 in page2 being:
while($row = mysqli_fetch_array($table))
To better explain my question, I have posted another question which can be found here:
Modifying MySQL table on different pages with scores from a HTML form
On page1 a temporary table is created and filled with data from a mysql database. I am trying to store this table into a $_SESSION variable so that I can put the table onto page2.
That's impossible.
And shouldn't be used anyway.
something wrong with your design. Most likely such a table is superfluous and you don't actually need it at all.
As of the real problem behind this one - better ask another question, explaining the real life task for which you decided to use a temporary table passed between pages.
Responding to your question one by one:
Error you are Getting
The error that you are getting normally is the result of incorrect spelling or reference of table name, field name or any other variable in the MySQL query. In your case, it may be due to incorrect calling/storing your Session Variable. For example,
//Instead of "table", you typed "tabel". This is just an example.
$result = mysqli_query($mysqli,"SELECT * FROM table");
Share your code so that I can try picking up this error. Above is just an example.
Storing values in Session Variable is not Recommended
Suppose your user fills in the form and moves on to the next phase. The data from the first phase is transferred to the second phase via Session Variable. What if the user simply closes the tab and restarts the process? Session Variable will still be set and the previous data may interfere with the new one and can produce unexpected results.
Ideal Solution
It is better to store the values in JavaScript Array and then transfer to the next page by Hidden Input field. Some of the benefits of using this logic are:
Fast Performance
More Secure
Easily Manageable
Reference Code
If you are taking the values from HTML Forms, then it is very simple to have the value in POST. Using the JQuery UI selection, you can add the selected values in a JavaScript Array.
//Declare Global JavaScript Variable on Page Load. This will be at the end of <head>
$(document).ready(function() {
window.fase1result = [];
} );
After this, on each click event where you want to add the data to be taken to the next page, use the following code to add the value to this array.
fase1result.splice(indexOf_to_add, 1, "SelectedValue");
To understand .splice better, click here.
One selection, e.g. clicking on a Div or link, add the value to a fase1result and on submit add the array value to Input Hidden by using the following:
Add a Javascript Function on form's onsubmit.
<form id="myForm" method="POST" action="fase2.php" onsubmit="return fase1Values()">
Add <input type="hideen" name="fase1values_input" id="fase1values_id"> in the form.
Below is the JavaScript onsubmit function just before </body>.
function fase1Values() {
$( '#fase1values_id' ).val( JSON.stringify(fase1result) );
}
Note that JSON.stringify is required in order to set the Array as an input value.
$decode_fase1result = json_decode( $_POST['fase1values_input'] );
Now you have transferred the fase 1 selection data using an Array from Page 1 to Page 2 without storing data in any temporary table.
Hope this answers your question and solves your problem as well.
I'm working on a page where I've listed some entries from a database. Although, because the width of the page is too small to fit more on it (I'm one of those people that wants it to look good on all resolutions), I'm basically only going to be able to fit one row of text on the main page.
So, I've thought of one simple idea - which is to link these database entries to a new page which would contain the information about an entry. The problem is that I actually don't know how to go about doing this. What I can't figure out is how I use the PHP code to link to a new page without using any new documents, but rather just gets information from the database onto a new page. This is probably really basic stuff, but I really can't figure this out. And my explanation was probably a bit complicated.
Here is an example of what I basically want to accomplish:
http://vgmdb.net/db/collection.php?do=browse<r=A&field=&perpage=30
They are not using new documents for every user, they are taking it from the database. Which is exactly what I want to do. Again, this is probably a really simple process, but I'm so new to SQL and PHP coding, so go easy on me, heh.
Thanks!
<?php
// if it is a user page requested
if ($_GET['page'] == 'user') {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
// db call to display user WHERE id = $_GET['id']
$t = mysql_fetch_assoc( SELECT_QUERY );
echo '<h1>' . $t['title'] . '</h1>';
echo '<p>' . $t['text'] . '</p>';
} else {
echo "There isn't such a user".
}
}
// normal page logic goes here
else {
// list entries with links to them
while ($t = mysql_fetch_assoc( SELECT_QUERY )) {
echo '<a href="/index.php?page=user&id='. $t['id'] .'">';
echo $t['title'] . '</a><br />';
}
}
?>
And your links should look like: /index.php?page=user&id=56
Note: You can place your whole user page logic into a new file, like user.php, and include it from the index.php, if it turns out that it it a user page request.
Nisto, it sounds like you have some PHP output issues to contend with first. But the link you included had some code in addition to just a query that allows it to be sorted alphabetically, etc.
This could help you accomplish that task:
www.datatables.net
In a nutshell, you use PHP to dynamically build a table in proper table format. Then you apply datatables via Jquery which will automatically style, sort, filter, and order the table according to the instructions you give it. That's how they get so much data into the screen and page it without reloading the page.
Good luck.
Are you referring to creating pagination links? E.g.:
If so, then try Pagination - what it is and how to do it for a good walkthrough of how to paginate database table rows using PHP.