Give value to Database by Pressing button - php

So i ran into some trouble not to long ago. As a student i am relativly new to programming and thus i often visit sites like these for help. My question is how can i add value to database by pressing a button. For me the problem here is that the button has a javavscript function to print. So in other words i want the button to have 2 functions, one that prints the page (which i already have) and one that adds value to the database. The purpose to adding the value to database is so people can see that its already been printed before.
So essentialy what i am asking for is how can i give a button 2 functions (one which is Javascript) and show people that the button is used(in this case, that it has been printed). All help will be appreciated very much.
My code is as following:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='window.print()' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>

This would aquire 2 tasks:
Is that you bind a function to the click handler of the button.
Although it is bad practice to use function calls directly, in your case this would be that you replace the window.print() by a custom javascript function.
In that javascript function, you execute the window.print() again, where-after you do the next step in the logic: sending data to PHP.
With ajax you can archieve this.
With a parameter in the function you can pass what the ID of the current row is, which need to be passed to PHP.
You need to create another PHP script, that will be called by tje AJAX script.
In that PHP script you will do the required updates to the database.

Ok There is a lot of ways you can do it but here is how i would do it :
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
//first you call a custom javascript function after the 'onclick'. I believe you'll have to pass a variable as an argument (like $id).
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
Then you write this function in the header of your page
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://www.domaine.com/directories/printed_table.php?id=" + id;
xmlhttp.send();
}
</script>
Then you write your file printed_table.php where you store 1 if printed or 0 if not printed. I don't understand german so i don't know where you store your printed variable but it goes like this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
This should work. Just be careful and check the $_GET['id'] before to use it for security purposes. like you can use the php function is_int(). Depending of the security level you need you might want to secure this code a little more.

Related

I have a button. When I press a button, one number reduces the number in the data base. I want it to be repeated every time

I have a button. When I press a button, one number reduces the number in the data base. I want when pressed each time it reduces the number by one
code html & php
<form method="post">
<div><?php
$username = "root";
$password = "";
$database = new PDO("mysql:host=localhost; dbname=testt;",$username,$password);
$ser = $database->prepare("SELECT * FROM test");
$ser->execute();
foreach ($ser AS $res){
echo '<h1>' . $res['NUMBER']; '</h1>';
}
?></div>
<input type="submit" name="click" value="click" id="click">
</form>
<?php
if (isset($_POST['click'])){
$username = "root";
$password = "";
$database = new PDO("mysql:host=localhost; dbname=testt;",$username,$password);
$tet = 12;
$update = $database->prepare("UPDATE test SET NUMBER=$tet-1 WHERE ID = 1");
$update->execute();
}
?>
Just use
SET NUMBER=NUMBER-1
to reduce the field by one from its current value. If you use $tet you will get 11 every time obviously because you hard coded it

PHP doesn't get results from database [duplicate]

This question already has an answer here:
Why does mysqli num_rows always return 0?
(1 answer)
Closed 6 years ago.
I want to make instant search (google like) on key up Jquery ajax must ass value from HTML input field to PHP and PHP must chec in SQL table named "title" for any words which Begin or Contain the written word/letter,if there isn't anything found it must print the results out in a div.
Here is an example:
The picture explains: Up is the input field and down box is the box for results to be printed,as we can see it is working,but PHP don't want to get data from SQL,and only printing the result for 0 value (Nothing Found) on Bulgarian language.
There is my code:
<?php
$hostname = "localhost";
$username = "shreddin";
$password = "!utf55jyst";
$databaseName = "shreddin_nation";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch = "";
if (!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$req->bind_param('s', $fsearch);
$req->execute();
if ($req->num_rows == 0) {
echo 'Не бяха намерени резултати!';
}
else {
while ($row = $req->fetch_array()) {
?>
<div class = "search-result">
<span class = "result-title">
<? php
echo $row['title'];
?>
</span><br>
</div>
<?php
}
}
}
?>
The code is working till else {...} only this part didn't work..;/
I tried to use echo some results after else {...} because i thought it was a problem with my code,but it didn't work either way ...Can somebody explain to me where is my mistake (with simple language please) i am not really good at coding exept with PHP.
I won't put Jquery and HTML here because all working fine there, the post method is all good, the problem is with the php. But of course if you need it to help me I will paste it with no problem.
Edited
$value = '%'.$fsearch.'%;
$req->bind_param('s', $value);
it will work :)
<?php
$hostname = "localhost";
$username = "username";
$password = "pass";
$databaseName = "dbName";
$connect = new mysqli($hostname, $username, $password, $databaseName);
$fsearch="";
if(!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$req = $connect->prepare("SELECT title FROM food_data_bg WHERE title LIKE ?");
$value = '%'.$fsearch.'%';
$req->bind_param("s", $value);
$req->execute();
$req->store_result();
if ($req->num_rows == 0){
echo 'Няма резултати';
}
else{
echo 'ДАА';
}
}
FINALY !!! that is the final result,it is printing ДАА when there is a result found and Няма резултати when there isn't any results fixed it after 1 month of pain lol Thanks to everyone which helped me <3<3 <3 <3 <3

Sending an array from PHP to javascript

In the PHP file can anyone help me directly making a for loop where I don't know the number of rows that are going to be selected.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
$index = 0;
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$myarray[$index] = $row["firstname"];
$index++;
$myarray[$index] = $row["lastname"];
$index++;
$myarray[$index] = $row["email"];
$index++;
}
}
else
{
echo "0 results";
}
$conn->close();
?>
The Javascript code contains javascript of a search bar suggestion code and here i didn't mention the typeahead javascript file
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
$('#the-basics .typeahead').typeahead({
hint: true, //here i used typeahead js code though i didnt mentioned here
highlight: true,
minLength: 1
}, {
name: 'states',
source: substringMatcher(states)
});
You can simplify the PHP a little bit here when you read in the values as you dont need to increase the index:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";//database details
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);//making a connection
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
$myarray = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myarray[] =$row["firstname"];
$myarray[] =$row["lastname"];//storing in the array
$myarray[] =$row["email"];
}
} else {
echo "0 results";
}
$conn->close();
?>
You could echo in the results to the Javascript where you require them, echo($myarray[0]) for example.
Your Javascript may look something like this:
var matches = <?php echo($myarray[0]); ?>
There are 4 ways you can do to insert dynamic content to your javascript code.
Make the javascript inline to your PHP page. That is, putting your js code inside <script> tags
Make the dynamic js variables global and populate them in your php page. Your separate JS files will be able to read these global js variables.
If you want to have a separate file for JS, you have to generate it everytime (because you cant have PHP code in javascript. The browser cannot interpret it, and the server cannot interpret it)
If you want to force the server to interpret PHP code in JS files, add a handler so that .js is handler by the php interpreter (whether php module or php-cgi) see Clean links to PHP-generated JavaScript and CSS

fetch_assoc doesn't show first row of results

Not sure what I did wrong. I'm aware that having two fetch_assoc removes the first result but I don't have such a thing.
$sql = "$getdb
WHERE $tablenames.$pricename LIKE 'm9%'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
}
My connect file:
$servername = "";
$username = "";
$dbname = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
require_once ('seo.php');
$dollar = '2.';
$euro = '1.9';
$tableformat = "<div class=\"CSSTableGenerator style=\"width:600px;height:150px;\"><table><tr><th>Name</th><th>Price</th><th><a class=\"tooltips\">Community<span>New !</span></a> </th><th>Cash Price</th><th>Trend </th><th>Picture </th></tr></div>";
$getdb = "SELECT utf.id, utf.PriceMin, utf.PriceMax, utf.Name, utf.Trend , community1s.price as com_price, utf.Name, utf.Trend
FROM utf
INNER JOIN (select id, avg(price) price from community1 group by id) as community1s
ON utf.id=community1s.id";
$tablenames = 'utf';
$pricename = 'Name';
$idrange = range(300,380);
What happens is, it fetches the first two column's fine and the rest of the row is not there and pushes the other results down one row, which messes up the data.
Here's an image to demonstrate:
http://imgur.com/CQdnycW
The seo.php file is just a SEO function.
Any ideas on what may be causing this issue?
EDIT:
My Output:
echo $tableformat;
while($row = $result->fetch_assoc()) {
$name = str_replace('m9', 'M9 Bayonet', $row['Name']);
include 'filename.php';
echo $dbtable;
EDIT: Solved it by moving my variables around. Marked as solved.
I found the issue. Some Variables that did the output were in a bad place. Rearranged them and now they are fine.
Your HTML is broken, and strange things happen in broken tables. $tableformat contains HTML that opens a <div> and a <table>, but then closes the <div> with the table still open.
Fix the broken HTML and you'll probably find that all is well

Passing JSON to Array in PHP

I'm working on a filter in which results are filtered right away, I'm wondering if that may be the cause of the problem so I thought I would ask and see if anyone could give me a pointer on how to proceed.
<script>
var services = [
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
while($row = mysql_fetch_array($result)) {
$url = $row["$url"];
$title = $row["$title"];
$amount = $row["$amount"];
$id = $row["$id"];
$status = $row["$status"];
$nonprofit = $row["$nonprofit"];
echo '{"permalink": "';
echo "{$url}";
echo '",';
echo '"title": "';
echo "{$title}";
echo '",';
echo '"amount":';
echo "{$amount}";
echo ',';
echo '"id": "';
echo "{$id}";
echo '",';
echo '"status": "';
echo "{$status}";
echo '",';
echo '"address": "';
echo "{$address}";
echo '",';
echo '},';
}
}
?>
]
//]]>
</script>
<script id="template" type="text/html">
<a title="{{title}}" href="{{permalink}}">
<div class="fs_box hide-for-small-down">
<div class="fs_left">
<span class="fs_head">{{title}}</span>
<span class="fs_id"><img src="images/{{id}}.jpg" width="75%" height="75%" onError="this.onerror=null;this.src='images/logo.png';"></span>
<span class="fs_status">{{status}}</span>
<span class="fs_disc">{{address}}</span>
</div>
<div class="fs_price">${{amount}}+</div>
<div class="clear"></div>
</div>
</a>
</script>
I'm expecting it to produce a bunch of results that then are filtered criteria which are elsewhere in the page.
When I try it currently just as a php code it outputs fine. However, when I try it in the php file that this should go in it produces nothing. Or does it dislike being in a script?
Thanks for any help!
You can use json_decode and json_encode to turn an array to json and json back to an array.
Also someone will probably mention that you should not be using the mysql_* functions in PHP as they are depreciated.
Something like this:
<?php
//Variables for connecting to your database.
//These variable values come from your hosting account.
$hostname = "###";
$username = "###";
$dbname = "###";
//These variable values need to be changed by you before deploying
$password = "###";
$usertable = "###";
$url = "permalink";
$title = "Address";
$amount = "rent";
$id = "id";
$status = "Beds";
$nonprofit = "Address";
//Connecting to your database
mysql_connect($hostname, $username, $password) OR DIE ("He's dead Jim");
mysql_select_db($dbname);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query);
if ($result) {
$results = array()
while($row = mysql_fetch_array($result)) {
$results[] = $row;
}
$json = json_encode($results);
}
?>
]
<script>
var services = <?php echo $json; ?>;
</script>
This would give you a json object to use to render in your script.
What extension is the file you are saving?
If it's not .php or an extension set to render php, then you'll just have the code show up as test.
You might want to pull out the "die" statement after the db connect. This looks like you are running php in a .js file so you probably want the entire file to write out rather than stop because you couldn't connect to the database (or at least give 0 results, maybe a warning)

Categories