Sending a certain cell from the database to another PHP page - php

I am trying to send a specific cell to a PHP page and deleting that row which contains this specific cell. But it appears I am doing something wrong.
This is how I sending the information:
echo "<td><a href='delete.php?id= '$row['pid']''>Delete</a>< /td>";
and using it like this:
$del = "DELETE FROM sca WHERE pid = $_GET['id']";
My database connections are working well but I couldn't manage to send the 'pid' integer to a PHP page.
Thanks

Probably you misstiped some character. Try with this :
echo "<td><a href='delete.php?id=".$row['pid']."'>Delete</a></td>";
echo '<td>Delete</td>';
echo "<td><a href='delete.php?id={$row['pid']}'>Delete</a></td>";
Try to keep this code mixture (html and php) readable or improve it for future changes and revisions.
Make sure to receive correct value in $row['pid'].
Also as advice you should protect your data and clean it before any db interaction.

Related

How to read a blob in Base64 using PHP and MySQL?

I am a newb with 6 months experience, self-taught via StackEx/books/etc. Created a pretty decent website with login/register and storing some info via mySQL. I have been through every single BLOB post here and I have some decent output.
I think I, like most newbs, know enough to be dangerous, don't have the greatest foundation laid out so when it gets to serious understanding of built-in functions, arrays and passing arguments we can lose the flow and I basically think I have dug a hole by using includes to call some navbar so that I can't just use a header to output the damn image as I echo the user name after login so it has already outputted lines and it will be a monster to undo. Three levels of nav, unauthenticated, authenticated and admin.
The database connection and write to/read from is OK. I can store the BLOB and I can even read it back and store the array in a variable and then debug see the binary but I can't get it to display on an HTML page.
Here is the fun:
$stmt = $dbc2->query("SELECT * FROM equip1");
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$name = $row['equipname1'];
$desc = $row['equipdesc1'];
$img = $row['equipimg1'];
}
<div class="col-lg-12">
<h1><?php echo $name ?></h1>
<p><?php echo $desc ?></p>
<pre>
<?php print_r($img); ?>
</pre>
<?php echo "<img src='data:image/jpeg;base64," . base64_encode( $img ) . "' />"; ?>
</div>
$dbc2 connects
equip1 table is two simple varchar cols, one BLOB col.
$name and $desc echo out ok, the $img displays broken link.
I check the array via pre code and is matching, per what is stored in dB during upload.
From what I have read and gone through, seems like you can't do this at same time unless via data URI which I have done but still broken link. Not making sense to me at all. I try the header and of course output already started but I can see also outputs the binary.
Here is screenshot of the URI method:
Since both methods "seem" to get into and out of the dB but do not display I'm going round in circles. Please help me out to display the image on an html page. I would like to echo it anywhere and then I can just style the page after that. Thanks!
Try Like this
<?php echo '<img src="data:image/png;base64,'.base64_encode($img).'">';?>
Uhh NEVER MIND. Never thought reading someones answer would make for "fresheyes". I noticed I was encoding but I already encoded it when I stored it. Mea culpa. DOH! :)

How to put MySQL table into session variable and using the table on next page?

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.

redirect to a content page when a link is clicked

ive just started PHP and MYSQL, and been trying to figure out how i can redirect to a page and display the content.
i have this PHP code that lists all my topic rows from my database
while ($row = $result->fetch_array()) {
echo '<p class="list" st>' . $row['topic'] . '<br />';
}
it will list all the topics inside the <a href> markup.
when link is clicked, i will be redirected to a page where the content is displayed based on the topic link.
i just need the logic how to create that page. basically i have page.php which i plan to put the logic. but i dont know how to start.
I suggest to use GET method to send ID of content to your page.php , url should be something like this :
http://site.com/page.php?id=120
And in your page.php get the id using $_GET['id'],i admit you have content in database , so you will display data based on this id.
PHP code :
while ($row = $result->fetch_array()) {
echo '<p class="list" st>' . $row['topic'] . '<br />';
}
An important thing , pay attention to sql injection especially when you get id.
Useful links about protecting from SQL injection:
-How can I prevent SQL injection in PHP?
-What's the best method for sanitizing user input with PHP?
-Protect against SQL injection
Essentially each link is going to need to carry a piece of information to page.php in order to tell that page what content to display. This is likely going to be some sort of identifier for the specific record. Something like this:
echo '<p class="list" st>' . $row['topic'] . '<br />';
This will make each link unique with an id parameter. Then, in the code on page.php you would check for that parameter as a query string value, which would be available here:
$_GET['id']
Remember that users can spoof this value and essentially put whatever they want into that link, so make sure it's a valid ID and make sure you don't use it directly in a database query without sanitizing the input first, otherwise users will have an open door to your database. (Read up on SQL Injection for more information.)
With that value, page.php will query the database for the one record which matches that ID and display the data from that record accordingly.
while ($row = $result->fetch_array()) {
echo '<a href="page.php?topic="'.$row['topic'].'><p class="list" st>' . $row['topic'] . '<br /></a>';
}
in the page.php make functions of one topic each and call that respective function for which the request has come

delete a row from my sql table

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);
}
}

Display database contents? PHP / MySQL

So I have a chatroom type of database where the text that a user inserts gets stored into a databse as their username in one field and their message in the other. I want to have my page output the database info, so that people can see each others messages.
How do I do this?
Also, is it possible to make a for loop that checks to see if the database has been updated with a new message, therefore it reloads the page? (Then the page outputs the database info again to update everyones messages)
Please help.. i'm so confused.
Take a look at MySQL functions in PHP manual. You need to connect to the server/database and run a select query to get the data from tables.
As for the loop: you could use JavaScript setInterval function and combine that with AJAX call to periodically poll for new records.
Like the others have said, you will want to connect to your database and then query the table that you have the data in.
while($row = mysql_fetch_assoc($results))
{
echo $row['username'] . " said: " . $row['message'] . "<br />";
}
I use mysql_fetch_assoc() instead of mysql_fetch_array() since the arrays are associative arrays (not indexed by integers, but rather by names (associations))
As for displaying the update on the page dynamically, that involves AJAX. Basically what that means is that your page will call out to a background script to get the new records from the database. This would require a new field in your 'messages' table, something like 'msg_delivered' that you could set to '1' when it has been fetched.
You should check out this if you are interested in making an AJAX chat client: http://htmltimes.com/javascript-chat-client-in-jquery.php
To read anything from a mysql database you would use the mysql_connect() and the mysql_query() functions
eg:
$link = mysql_connect('localhost', 'root', '');
$results = mysql_query('select * from messages');
while($row = mysql_fetch_array($results))
{
echo $row['username'] . ': ' . $row['message'].'<br />';
}
To display new messages the best way would be to use AJAX and poll the database from there, either loading a separate page into a DIV or getting XML back and placing into HTML tags. I would recommend using JQuery for these kinds of tasks. Check http://www.sitepoint.com/article/ajax-jquery/ for an example.

Categories