wrap a mysql query in a php function and print results - php

I have the following query that I ran on my database to remove some data:
delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;
But I now need to make the a php function that runs when I press a button called clean
then print out all the subscriber data that was deleted.
Not quitesure where to start with this.
this is my html so far:
<form id="form1" name="form1" method="post" action="">
Clean subscribers:
<input type="submit" name="clean" id="clean" value="Clean" />
</form>
Any help or advice with this is very much appreciated.
C

You'll need the button to submit a form to a handler page, the handler page would then run the query, and collect+print the data.
If you don't want to refresh the page (or have your users diverted into another page), you'll want to use Ajax.
That's where you start.

Is abvious you made no effort! but I will answer you anyway.
<?php
$con = mysql_connect("serverUrl","login","password");
mysql_select_db("dbName", $con);
$result = mysql_query("SELECT * FROM subscriber, subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
while($row = mysql_fetch_array($result))
{
echo $row['subscriber.name']; //assuming you have a field {name} in your table
echo "<br />";
}
mysql_query("delete subscriber, subscription from subscriber,subscription where subscription.status = 0 and subscription.snid=subscriber.snid;");
?>

First you'll need to select the data you're about to delete.
Then you'll need to delete it and return the selected rows.
$rows = array();
mysql_connect(...);
$res = mysql_query(...select query here...);
while($row=mysql_fetch_assoc($res)) {
$rows[] = $row;
}
$res = mysql_query(...delete query here...);
return $rows;

You might not want to totally delete the subscriber. If I were you I would include a field named "deleted" or something along those lines, indicating whether or not the subscriber has been deleted. Then query according to whether or not that field is true or false.

Related

php mysql show result one after another

I wanna build a presence check for our choir in the style of tinder but not as complex.
The database contains names and file paths of pictures of the members. When you click on the "present" or "not present" button, the next picture and name should be shown. In the background, the database table should be updated with true/false for presence. (this will be done later)
My problem is that it almost works, but instead of showing one member, it shows all members with their pictures in one single page.
I understand that I could fire with Javascript to continue and paused php-function but I don't get the clue how.
I tried "break" in the php and call the function again but that didn't work.
<?php
$conn = new mysqli(myServer, myUser, myPass, myDbName);
$sql = "SELECT * FROM mitglieder";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<img class='pic' src='" .$row["folder"]. "/" .$row["img"]. "'><br>" ;
echo "<div id='name'>" .$row["vorname"]. " " .$row["name"]. "</div> <br>";
echo "<img src=''img.png' id='present' onclick='isPresent()'>";
}
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<script>
$( document ).ready(function() {
console.log("Ready");
);
</html>`
You can use php function
mysqli_fetch_all()
assign it on the variable outside the while loop and loop or access the indexes in your code.
For Example:
$data = mysqli_fetch_all();
echo $data[0]['name'];
foreach($data as $item)
{
echo $item['name'];
}
You need a way to establish a "state" between your web page and the PHP backend so that you can step through the data. I suggest something like this:
Use an auto-increment integer primary key for the database. That way you can access the data in index order. Let's name the column id
Have your JS code send a form variable - named something like LAST_ID to the PHP in your get. i.e http://someurl.com/script.php?LAST_ID=0
On your first call to the server, send LAST_ID = 0
In your PHP code, fetch the value like this: $id = $_GET('LAST_ID');
Change your SQL query to use the value to fetch the next member like this:
$sql = sprintf("SELECT * FROM mitglieder where id > %d limit 1", $id); That will get the next member from the DB and return only 1 row (or nothing at the end of data).
Make sure to return the id as part of the form data back to the page and then set LAST_ID to that value on the next call.
You can use a HTTP POST with a form variable to the server call that sets that member id to present (maybe a different script or added to your same PHP script with a test for POST vs GET). I suggest a child table for that indexed on id and date.
I hope that puts you in a good direction. Good luck

How to check if there is data under $_POST?

Im writing a page in HTML and PHP that connects to a Marina database(boats,owners etc...), displays all of the owners last names in a drop down list and then displays all the boats under the last name that was chosen.
here is my relevant code...
$sql = 'select LastName from Owner';
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$values[] = array(
'LastName' => $row['LastName']
);
}
echo '<form align="left" top="200" action="page2.php" method="post">
<p>Select an owner:</p>
<select top="200" name="form1" id="form1">';
foreach($values as $v){
echo '<option value="'.$v['LastName'].'">'.$v['LastName'].'</option>';
}
echo '</select>
<input type="submit" value="Submit">
</form>';
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = '.$form1;
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values[] = array(
'BoatName' => $row['BoatName']
);
}
echo '<ol>';
foreach($values as $v){
echo '<li>'.$v.'</li>';
}
echo '</ol>';
}
I have managed to properly display the last names in the drop down list and keep the name chosen as a variable but I am running into a few errors that I cannot solve.
1) when I attempt to reload the page(using Firefox) I get a message "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier" So i was wondering how I could code it so that I don't need to have data being sent initially.
2)After a last name is submitted and I attempt to run a query to match all the boats under that last name I get an error that the $result variable is not a MYSQLI result type even though I used the same code earlier in the script.
I am new to HTML and PHP so any help is greatly appreciated.
That message happens when you reload a page that was the result of a form submission. It means it has to resubmit the form to reproduce the same result. The way to prevent it is to have the form redirect the user to a page that displays the result, rather than displaying the result itself. This can be complicated unless the form submission just makes a change to the database, and then you want to display the contents, rather than display something dependent directly on the form submission.
You need to put quotes around the name:
$sql = 'select BoatName from MarinaSlip,Owner where MarinaSlip.OwnerNum = Owner.OwnerNum and Owner.LastName = "'.$form1.'"';
But it would be better to use a parametrized query. See How can I prevent SQL injection in PHP?

Writing single page logging tool in php

Im making a small php webpage which I plan to use to track on which subjects a helpdesk receives calls. My database has 3 important fields: id, name, and amount for each subject.
On my page I have a form with a dropdown list where you select a type of call and click submit. The idea is that every time you click submit the page reloads and the amount in the database for the chosen id is heightened by 1.
The form gives me the id and name for each call:
<form method="post" action="index.php">
<select class="select" id="calltype" name="calltype">
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value=".$row["ID"].">".$row["NAAM"]."</option>".PHP_EOL;
}
}
?>
</select></br>
<input class="input" type="submit" name="Submit" value="Submit">
</form>
This part works, if I echo $_POST['calltype'] I get the correct ID. What I can't get to work is the update statement which I want to heighten the counter, like:
if(isset($_POST['calltype']{
mysqli_query("UPDATE calls SET amount=(amount+1), WHERE id = $_POST['calltype']");
}
How would I go about this? I tried several methods but can't get it to work
besides for the extra comma, interpolation with the POST array like this is risky. maybe try:
mysqli_query("UPDATE calls SET amount=(amount+1) WHERE id = " . mysqli_real_escape_string($link, $_POST['calltype']) . " ;");

Display more from database on click PHP, JQUERY, MYSQL

I'm working on a website and am pulling category names from a db table (category_names). I then display them on the website using php on to an html unordered list. I want to limit the number of category_names and then using jquery(or anything else but I prefer jQuery) retrieve more category_names and add a less button to go back.
I hope I made this question easy to understand, and thank you for any help!
Basically use AJAX to pull in more. Start off by loading in a few by using LIMIT.
<ul id="categories">
<?php
$res = mysql_query('SELECT * FROM `category_names` LIMIT 10'); // change limit to suit
while ($row = mysql_fetch_array($res)) {
echo '<li>'.$row['name'].'</li>'; // or whatever your field is called
}
?>
</ul>
<span id="loadmore" num_loaded="10">Load More</span>
Then use the following jQuery to load more:
$('#loadmore').click(function() {
var loaded = $(this).attr('num_loaded');
$.ajax({
url:'load_categories.php',
type:'get',
data:{'from':loaded,'to':loaded+10},
success: function (res) {
var categories = $.parseJSON(res);
categories.each(function() {
$('#categories').append('<ul>'+this+'</ul>');
});
$('#loadmore').attr('num_loaded',loaded+10);
}
});
});
Finally you'll need to create the PHP page that the AJAX calls - load_categories.php
<?php
if (!isset($_GET['from'])) exit;
if (!isset($_GET['to'])) exit;
$from = $_GET['from'];
$to = $_GET['to'];
$diff = $from-$to;
// connect / select db
$res = mysql_query('SELECT * FROM `category_names` LIMIT '.$from-1.','.$to.';');
$arr = array();
while ($row = mysql_fetch_array($res)) {
array_push($arr,$row['name']);
}
echo json_encode($arr);
?>
There are a number of different approaches that work better or worse depending upon your needs.
Approach 1 (simpler, less efficient, scales poorly): execute the full query, and store all of the results on the DOM, just hiding them using jQuery (jQuery expander is a simple plugin you may want to try out, though I have found it limiting in customization).
Approach 2 (more complicated, but more efficient/scalable, also faster): Use MySQL limit, you can actually send a second mysql request on click, however, you would want to make sure this is asynchronous so as to not delay the user's interactions.
http://php.about.com/od/mysqlcommands/g/Limit_sql.htm
This is similar to: PHP/MySQL Show first X results, hide the rest
Or you could do something simpler:
$get = mysqli_queury ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 5"
if (isset($_POST['button']; {
$get = mysqli_query ($link, "SELECT * FROM db_name WHERE blank='blank' LIMIT 10"
}
?>
<form action="showmore.php" method="POSt">
<input type="button" id="button" name="button">
</form>
Hope that helps!
Use a datagrid with pagenation. I think datatable JQuery pluggin will work well for you

submit one or another query

I'm continuing to hack away at my newbie php/mySQL 'Invoicer' app.
I now have a form page in which I want to run one of two queries - either an INSERT or an UPDATE, depending on whether an ID is present. When present,
the ID is used to retrieve the record and pre-populate the form accordingly, which I have working. My problem now is that my conditional bits are
obviously not right because in either case when submitting the form the INSERT query is run, can't get the UPDATE to run, and I've exhausted my
understanding (and guess-ology).
I'd love to know why this ain't working, even if it's not the best approach, and I'm definitely open to suggestions to move the queries to a process.php,
etc. I'm also wondering if I should use 'if(isset($_GET['ID'])' to simply include one block or the other.
Many thanks in advance for any help or suggestions. (p.s. my intention is to overhaul for best practices/security once I've got the broad strokes wired up)
cheers, s
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
and:
<form id="invoiceData" method="post" action="/html/form.php">
When you submit the form, you need to include the ID again, otherwise it is silently dropped off since you are posting to the hard-coded value /html/form.php (with ID removed). This will cause the empty($_GET['ID']) part to match and run, causing the INSERT. You can simply include the ID value back into the action of every form post like this:
<form
id="invoiceData"
method="post"
action="/html/form.php?ID=<?php echo $_GET['ID']; ?>"
>
This should work in both the cases of the UPDATE and the INSERT, because if there was no ID to begin with, this will render as /html/form.php?ID=, which will match the case of ID being empty, I believe. You may want to test this logic out for sure.
Hope this helps!
$_GET[ID] will be set if you pass it as a URL parameter. So if you change your <form> action to
<form id="invoiceData" method="post" action="/html/form.php?ID=12">
Where 12 is whatever ID you want, you should be getting the results you're wanting -- as long as you do have a <input type="hidden" name="submit" value="1" /> (value can be whatever) in your form somewhere as well.

Categories