I've had this problem for a couple days now and I've been trying different things to attempt to fix it and I'm not getting anywhere. Basically I'm pulling in data from a database, displaying the data using a loop, adding a "delete" button, and storing the data in a session array.
When the user presses the delete button the page refreshes but my session variable isn't being updated. Can anyone tell me why? I'm using the if isset 'POST' to update my session variable. FYI there's a lot of extra echoes in my code just so I can see what's going on. Any suggestions would be greatly appreciated. I also threw in a JavaScript popup to see if the if statement was working. The popup is not coming up either.
<?php
function multilineQ($con, $sql)
{
$x = 0; // incremented for the ex number
if (mysqli_multi_query($con,$sql))
{
do
{
// Store first result set
if ($result=mysqli_store_result($con))
{
while ($row=mysqli_fetch_assoc($result))
{
$button = "ex" . $x . "Button";
echo "<ex id=\"ex$x\">";
echo $row['ExType'] . ' ----- ' . $row['ExName'] . " " .
"<input type=\"submit\"
name=\"$button\"
value=\"Delete\"> " .
" - <b>Button Name: </b>" . $button;
echo "<br />";
echo "</ex>";
// Add to Array
// ----------------------
$_SESSION['exArray'][$x][0] = 1;
$_SESSION['exArray'][$x][1] = $row['ExType'];
$_SESSION['exArray'][$x][2] = $row['ExName'];
// ----------------------
// If delete button pressed...
// ----------------------
echo "$button If statement created <br /><br />";
if (isset($_POST['$button']))
{
$_SESSION['exArray'][$x][0] = 0;
$foo = "Alert: " . $_SESSION['exArray'][$x][3] . " : Deleted.";
echo "<script type='text/javascript'>alert('$foo')</script>";
}
// ----------------------
$x++; // Increment number
}
mysqli_free_result($con);
}
} while (mysqli_next_result($con));
} else
{
echo 'Could not run SQL...';
}
}
?>
you need add the session_start() on the first statement.
<?php
here> session_start();
function multilineQ($con, $sql)
{
Related
I have a page that shows gigs from database. First load only shows the title of each entry, and a button to show the full details, and a button to delete (not yet utilized)
I am having trouble passing on the ID value for each entry of my foreach loop. It always passes on the ID number of the last entry, no matter which one I click. So I always see the details of second gig, even if I click the first one. (I just have two gigs in the database for now)
Any suggestions how to pass on the ID of the one I click the SHOW button on?
This is my code
require_once "gigPDO.php";
//Show button is pressed
if (isset ( $_POST ["show"])) {
$id = $_POST ["id"];
//$id = 5;
try {
$dbase = new gigPDO();
$result = $dbase->searchGig($id);
//print_r($result);
foreach($result as $gig){
print("<p>Title: " . $gig->getTitle());
print ("<br>Venue: " . $gig->getVenue());
print ("<br>Date: " . $gig->getDate());
print ("<br>Time: " . $gig->getTime());
print ("<br>Country: " . $gig->getCountry());
print ("<br>Address: " . $gig->getAddress());
print ("<br>Postcode: " . $gig->getPostcode());
print ("<br>City: " . $gig->getCity());
print("<br>Description: " . $gig->getDescription() . "</p>");
echo "<br />";
unset($_POST ["show"]);
echo "<a href='searchGigs.php'>Back to list</a>";
exit();
}
exit ();
} catch ( Exception $error ) {
print("<p>Error: " . $error->getMessage ());
exit ();
}
}
//First load, shows all gigs
try {
$dbase = new gigPDO();
$result = $dbase->allGigs();
foreach($result as $gig){
print("<p>". $gig->getTitle(). "<p>");
print ("<input type='hidden' name='id' value='".$gig->getId() ."'>");
print('<input type="submit" name="show" class="next show-button" value="Show" />');
print(' <input type="submit" name="delete" class="next show-button" value="Delete" />');
echo "<br />";
echo "<br />";
}
if ($dbase->getRows() == 0){
print("There are no gigs in the database yet");
}else{
print("<p>Total " . $dbase->getRows() . " gigs</p>");
}
} catch ( Exception $error ) {
print("<p>Error: " . $error->getMessage ());
}
If you use a button instead of an input type="submit", then you can imbed the id into the button instead of using the hidden input.
echo '<button type="submit" name="id" class="next show-button" value="'.$gig->getId().'" />
Show
</button>';
The way you're doing it currently could work, but you would need a separate form tag around each set of inputs. Currently, when you submit your form, all of those hidden inputs are submitted, and since they have the same name, you get the value of the last one. Doing it the way I suggested, only the value of the button you clicked will be submitted.
I am writing a script to try and help make my day to day work easier. It works in parts, sending requests to an API and receiving responses. I then want it to save said responses in a text file that will be automatically emailed to a defined mailbox. The bit I am stuck with, is actually making my script save to a text file.
This is my script: (I'm not very experienced.. the include files aren't relevant, as they send requests the the API and contain nothing else.) I'm hoping that i can literally add a line at the bottom after the SQL connection closes to tell it to save to the text file. Also, I would like the text file to take the name of the "$CorrectCLI" variable.
Any help is appreciated. Cheers.
// Check connection
if(mysqli_connect_errno()) {
echo "Could Not Connect, Contact Support.";
exit;
} else {
echo "Connected to Database Successfully.<br><br>";
}
//Required Information:
$CorrectCLI = $CLIrow[0];
$CorrectSitename = $SiteNamRow[0];
$CorrectSiteNumber = $SiteNumRow[0];
$CorrectIP = $IProw[0];;
$xrefFromKF = "503269";
echo nl2br("Affected XREF: " . $xrefFromKF . "\n");
$CLIquery = "select primary_cli from customers where xref = " . $xrefFromKF . "";
$CLIresult = mysqli_query($con,$CLIquery);
if(!$CLIresult) {
echo "Could Not Locate CLI In Database.<br>";
}
$CLIrow = mysqli_fetch_row($CLIresult);
$CLI = $CLIrow[0];
echo nl2br("Circuit CLI: 0" . $CLIrow[0] . "<br>");
if(!$CLI > 0 ) {
echo " Could Not Locate CLI.<br>";
}
$IPquery = "select manufacturers_ip_prim from customers where primary_cli = " . $CLIrow[0] . "";
$result = mysqli_query($con,$IPquery);
if(!$result) {
echo "Could Not Locate Management IP.<br>";
}
$IProw = mysqli_fetch_row($result);
$IPcount = $IProw[0];
echo nl2br("Circuit IP: " . $IProw[0] . "");
if(!$IPcount > 0 ) {
echo " Could Not Locate Management IP.<br>";
}
echo nl2br("\n\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output1, $result1);
if ($result1 == 0) {
echo nl2br("Circuit Recovered - Cancelled Diagnostics.");
} else {
echo nl2br("Circuit Down - Starting Diagnostics");
// Perform Sync Check
include '../diags/SyncStatus.php';
// Perform Data Port Reset
include '../diags/DataPortReset.php';
// sleep(10);
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output2, $result2);
if ($result2 == 0) {
echo nl2br("Circuit Recovered - Stopping Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Continuing Diagnostics\n\n");
include '../diags/Metascript.php';
include '../diags/TAMtestSubmit.php';
include '../diags/TAMtestRetrieve.php';
echo "<br>";
include '../diags/GetProfile.php';
echo "<br>";
include '../diags/ProfileOverride.php';
echo "<br>";
// sleep(300);
include '../diags/RevertProfile.php';
echo "<br>";
echo nl2br("\nPinged " . $IPcount . "...\n");
exec("ping -c 2 " . $IPcount, $output4, $result4);
//print_r($output4);
if ($result4 == 0) {
echo nl2br("Circuit Recovered - Stopping End Of Diagnostics.");
} else {
echo nl2br("Circuit Still Down - Requires Attention.\n\n");
}
}
}
// Close the Database Connection
$conn->close();
?>
I would use the PHP output buffer.
Add this code to the top of this PHP script
ob_start("process_output");
function process_output($buffer){
$pageContent = $buffer;
// $pageContent is all the output of your web page,
// put your email logic here
return $pageContent;
}
In your logic I would reference http://php.net/manual/en/function.file-put-contents.php
Thank you for reading this, I am building a shopping cart with PHP session, when I click the submit button on the form, the $_POST was able to pass the value to the $_SESSION[''] array, but when I click the submit button again, the $_SESSION array only contain my last $_POST variable and the previous variables are all gone. As a shopping cart, the session array suppose to contain every data obtain from the POST value.
I checked with the SESSION_ID, which was able to shows the same ID when I submit the form, the var_dump shows the current SESSION array works (except only showing the last item). Please help me what is wrong in my code in order to keep the value into the SESSION array, thank you.
here is the full code, the sqli_query was replaced to specify item_id for troubleshooting, also this php will be included in another php that have an id in url, which seems irrelevant to this matter, but just for your information.
<?php if(!isset($_SESSION)){session_start();}?>
<?php
//if(isset($_GET['id']) && !empty($_GET['id'])){
require 'connecttosql.php';
$result = mysqli_query($con,"select COLOUR_EN, COLOUR_ZH, SIZE FROM mydb.item join mydb.colour using(item_id) join mydb.size using(item_id) WHERE ITEM_ID='T76'")
or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$size[] = $row['SIZE'];
$colour_zh[] = $row['COLOUR_ZH'];
$colour_en[] = $row['COLOUR_EN'];
}
mysqli_free_result($result);
mysqli_close($con);
for($x=0;$x<count($colour_zh);$x++){
$colour[$x] = $colour_zh[$x] . "/" . $colour_en[$x];
}
echo "<form action='' method='POST'>";
echo "<ul>";
echo "<li>size: </li>";
echo "<li><select name = 'size'>";
foreach(array_unique($size) as $sizeli){
echo "<option value = '" . $sizeli . "'>" . $sizeli . "</option>";
}
echo "</select></li>";
echo "<li>colour: </li>";
echo "<li><select name = 'colour'>";
foreach(array_unique($colour) as $COLOURli){
echo "<option value = '" . $COLOURli . "'>" . $COLOURli . "</option>";
}
echo "</select></li>";
echo "<li><input type='SUBMIT' name='submit' value='ADDTOCART'></li>";
echo "</ul>";
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
if(isset($_POST['submit'])) {
$_SESSION['size'][] = $_POST['size'];
$_SESSION['colour'][] = $_POST['colour'];
// $_SESSION['id'] = $_GET['id'];
}
echo SESSION_ID();
var_dump($_SESSION['size']);
var_dump($_SESSION['colour']);
// var_dump($_SESSION['id']);
/*
}else{
include 'index.php';
die();
}
*/
?>
You reinitialize (and therefore reset) the arrays at every request:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
Add a check like this:
if(!isset($_SESSION['size'])) {
$_SESSION['size'] = array();
}
if(!isset($_SESSION['colour'])) {
$_SESSION['colour'] = array();
}
it looks like you are resetting your session variables before it gets to this line...
if(isset($_POST['submit'])) {
try checking for existance of these before resetting...
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
While doing this:
$_SESSION['size'] = array();
$_SESSION['colour'] = array();
you are doing a reset to $_SESSION['size'] and $_SESSION['colour'].
You can replace it with:
if(empty($_SESSION['size'])) $_SESSION['size'] = array();
if(empty($_SESSION['colour'])) $_SESSION['colour'] = array();
or just delete these two entries.
Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?
Okay, been thrashing around with this for longer than I care to think about!
I am trying to drag event data from mysql so that it displays the Event Name once and several products under that Event Name
For Example:
Event Name
product 1
product 2
product 3
What is currently happening is that the Event Name is displayed above each product, like this
Event Name
product 1
Event Name
product 2
Event Name
product 3
The PHP Code is:
<?php
// Get the search variable from URL
$var = #$_GET['q'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=10;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("xxxxxxxx","xxxxxxxx","xxxxx"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("event_db") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "select * from event where event_name like \"%$trimmed%\"
order by event_name"; // EDIT HERE and specify your table and field names for the SQL query
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
// google
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the
search on google</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "Results<br /><br />";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["event_name"] . "<br />";
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "<b>$title</b>";
echo "$count $title2";
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a>  ";
}
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// $pages now contains int of pages needed unless there is a remainder from division
if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
// not last page so give NEXT link
$news=$s+$limit;
echo " Next 10 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Any thoughts would be greatly received.
simply use group_concat -> group_concat query performance
details -> http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
newbie including myself, please try google before posting the question
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
if($row["event_name"] != $lasteventname){
$title = $row["event_name"] . "<br />";
$lasteventname = $row["event_name"];
echo "<b>$title</b>";
}
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "$count $title2";
}