Update database information with onClick function - php

I am trying to update a tables row site_active in mysql using an onClick function with a button.
My button code is:
<button onClick='site_active()' id='site_active'><?php echo $client->site_active; ?></button>
And then of course my Script is:
<script>
function site_active()
{
alert("Site Updated");
}
</script>
I am sure that I need to use a php function to make this happen and I have the following code from my attempt to just do it with a form.
<?php
$con=mysqli_connect("INFORMATION REMOVED");
//Check connnection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con, "UPDATE mypanda_clients SET site_active='$_GET[site_active]' WHERE id='$_GET[id]'");
mysqli_close($con);
?>
The form option did not work because of some clashing problems in the website. ANY help would be great as I have spent hours on this with no progress. Thank You.

I would rather use jquery and do an ajax request to the server
$('#buttonid').click(function(){
//ajax request to the server goes here
});
Here the link for ajax in jquery
http://api.jquery.com/jQuery.ajax/

Related

Button onclick event triggered on every page load

I have a button which has a onclick attribute which calls a function. My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.
I've tried different variatons of syntax but nothing worked. I swapped 'button' for 'input type=button' but that didn't help anything.
this is in books.php
$sql = "SELECT books.id, books.name as bookname, authors.name as authorname, autori.surname, genre, description, stock FROM books JOIN authors ON books.author_id=authors.id ORDER BY books.name ASC";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>Name of the book</th><th>Author</th><th>Copies available</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["bookname"]."</td><td>".$row["authorname"]." ".$row["surname"]."</td><td>".$row["stock"]."</td>";
if (isAvailable($row["id"]) && isset($_SESSION["id"])) {
?>
<td><input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>"></td></tr>
and I'm calling the function borrowBook from functions.php which looks like this.
function borrowBook($idbook) {
$servername = "aaa";
$username = "bbb";
$password = "ccc";
$dbname = 'ddd';
$iduser = $_SESSION["id"];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE books SET stock = stock - 1 where id = " . $idbook;
$conn->query($sql);
$sql = "INSERT INTO reservations(id, dateBorrowed, dateReturn, returned, kniha_id, uzivatel_id) VALUES (NULL, NOW(), DATE_ADD(NOW(), INTERVAL 34 DAY), 0, $idbook, $iduser)";
$conn->query($sql);
}
So the SQL query and everything actually works. When I check the database I actually get new entries and everything is as expected. The only problem I'm having is that the button's onclick event is always triggered on every page load and I can't seem to fix it. From searching online everybody is using stuff like JavaScript or jQuery so it didn't really help me.
Hi and welcome to Stack Overflow!
Looks like you are trying to call php function from the client (browser). This is however impossible.
The way the PHP works is, that it prepares the content for the client and sends it to the client. After it is send, you cannot interact with the PHP code anymore. What you need to do is make client send another request.
My problem is that whenever the page loads it automatically triggers the onclick event without me clicking on anything.
The page load does not trigger onclick event. The PHP looks for all <?php and runs the code inside it even before it is sent to client.
How to do it?
You need to change the infrastructure a bit. For the beginning i'd suggest not using JS at all, but instead create second PHP page, that just does the borrowBook using GET parameter (you can expand it later) (See PHP's $_GET)
First you need to actually create the second page (let's call it borrowBook.php)
This page will get book's id using GET parameter (let's call that bookid)
This page's code may look something like this (Note: code is not tested)
<?php
borrowBook($_GET["bookid"]);
header("Location: /books.php");
?>
And now you need to change original code's line
<input type="button" value="Borrow" class="button" id="btnBorrow" onclick="<?php borrowBook($row["id"])?>">
To something like this
Borrow
What this does is, that PHP sees <?= and run the code inside it (in this case replaces the <?= ?> section with value of $row["id"]. Which if id is 1 will result in this:
Borrow
Sorry for my bad english.
You should use js (or jquery) in onclick handler that call your php-script with ajax.
PHP scripts works only in server.
Like this (jquery example):
<button id="handled-button">Click Me</button>
<script>
$('#handled-button').click(function() {
$.get('/myscript.php');
});
</script>
And in myscript.php call your function.

HTML PHP (Why does not return value?)

I was actually trying to retrieve the input submit button value. But I don't know why it does not work. Can anyone help me?
When the user click the buttons, the button's value will be send to the next page.
<?php
include('connect.php');
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userauth";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
?>
<html>
<head>
<title>GAF APPS</title>
</head>
<body>
<form method="post" action="branch.php">
<input type="submit" name="submit" value="<?php echo $row["Company"]; ?>">
</form>
</body>
</html>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is where I was going to retrieve the value:
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
You don't have an input named "action", therefore the isset() will never happen which is why you did not get an error for it
Having added an else condition for it, would have shown you that instead.
When debuging in PHP I tend the use the shotgun approach and output everything that could be remotely interesting and then narrow it down.
So when looking at parsing form variables use echo var_export($_GET, true) or vardump($_GET).
Not sure if GET or POST? Use _REQUEST which has both in 1 variable.
Use the HTML tag to make it more readable and htmlspecialchars() to convert characters that would normally be invisible because of your browser.
Using those will make it far easier to see what you are doing with your form.
So to answer the above question:
Look at the the mentioned request variables and determine by looking at the HTML and the code if the expected variables should be parsed and send by the browser when the submit button is pressed.
AND
See if the values actually received by PHP will have the expected outcome when handled.
Try to keep those 2 things separate, because what is in your HTML now does not mean it was there when you parsed the form. That's a bit of a bind when developing with PHP/HTML and forms, when you change the code and do not fully reload, but just press Submit on the form:
the code that will parse the current form will be changed, but the contents of the form parsed are the ones that where loaded in your browser and might be out dated.

Process database delete action in the same PHP page with post

I'm building PHP application for process employee leave records. In this application the main screen populate database records and action buttons. when user click the action button it take the database id from the table and go through another file to delete that record and then redirect back to the same page. This mechanism implemented using HTML _GET method. that means anyone can see the row ID in the URL feed and if anyone request this url with different row ID, PHP file delete the record since any other security measures not taken place in to prevent that. and also this application not using any kind of session.
this is my href code for the task I mentioned above.
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
and this is my rejectone.php code
<?php
$lid =$_GET['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = '$lid'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $id);
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
header( "refresh:0;url=bs.php" );
?>
I have two questions
1.) How can I run the rejectone task inside the same PHP file without redirecting to another PHP file
2.) How can I use HTML _POST method instead of get method to transfer data if I still use jejectone.php file
thanks!!
First of all change your line:
echo "<a href='rejectone.php?id=$lvid' class='btn btn-danger btn-xs m-r-1em'>Cancal</a>";
to
echo 'Cancal';
If you haven't included jQuery on your site, you can do it by adding this script to your page, just before closing
</head> tag
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
Add this JavaScript file to the bottom of your page, just before closing </body>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.delete-item', function(e){
e.preventDefault();
if(!confirm('Are you sure you want to delete this item?')) return false;
$.post('bs.php', {'id': t.attr('primary-key'), 'delete_item': 1}, function(e){
window.location = 'bs.php';
})
})
})
</script>
Copy your rejectone.php to bs.php, but make these changes:
if(isset($_POST['delete_item']))
{
$lid = (int)$_POST['id'];
include 'database.php';
$accval = "Accept";
try {
$query = "UPDATE leavesrecords SET leavestatus = 'Reject' WHERE lvid = :lid ";
$stmt = $con->prepare( $query );
$stmt->bindParam(':lid', $lid );
$stmt->execute();
}
catch(PDOException $exception){
die('ERROR: ' . $exception->getMessage());
}
}
That is it.
Use ajax post method. See Full example of accepted solution with sample code for more details here : Delete MySQLi record without showing the id in the URL
Then using jquery remove that record from the page which will give more good UI experience.

MySQL update query using AJAX and PHP

Scenario: I'm trying to incorporate it so that when you click this button, it adds 1 to a value in the database.
I've read so many articles about AJAX today but no solution.
P.S. The query works fine directly from the command line.
This is what I've written so far but I think I'm completely missing something.
game.php
<script>
function logCountAdd(){
var request = $.ajax({
type: "GET",
url: "logCountAdd.php"
});
request.done(function(msg ) {
alert('Success');
return;
});
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
};
</script>
</head>
<body>
<button type="button" onclick="logCountAdd()">Gather Resources</button>
logCountAdd.php
<?php
$connection = mysqli_connect("localhost","root","","users");
if (mysqli_connect_errno())
{
echo 'NOT_OK';
}
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
mysqli_close($connection);
echo 'OK';
?>
Problem: After I click the button, the value in the database does not change.
The Error Code: GET logCountAdd.php 500 (Internal Server Error)jquery-1.11.2.min.js:4 m.ajaxTransport.sendjquery-1.11.2.min.js:4 m.extend.ajaxgame.php:7 logCountAddgame.php:22 onclick
First question asked on here, sorry guys!
mysqli_query($connection, "UPDATE uc_users
SET logCount = logCount + 1
WHERE user_name='Gregory'";)
^ misplaced semicolon
move it to after the close parenthesis. You may want to turn on error reporting to make debugging easier
error_reporting(E_ALL);
ini_set('display_errors','On');

no results in inserting values to MySQL with AJAX

on my research site, I have a few radio buttons and I want to send their values to MySQL table using jquery and AJAX. All buttons and jquery code are put in single-project.php (I modified WordPress theme) and the bits of code that should handle interaction with the MySQL are put in the db.php in the same folder.
However, something is not in order, because values do not appear on the database table. Could someone help?
jquery:
//the last button
$('#submit_last_button').click(function(){
SomeVariable = $('input:radio[name=lastRadio]:checked').val();
if (!$("input:radio[name=lastRadio]").is(":checked")) {
$("label#lastRadio_error").show();
$("input#lastRadio").focus();
return false;
} else {
if ('input:radio[name=lastRadio]:checked')
$('#PreviousButtonDiv').hide();
$('#NextDiv').show();
$.post('db.php',{action: "submit_last_button", previous_variable:SomePreviousVariable, last_variable:SomeVariable},function(res){
$('#result').html(res);
});
}
});
});
db.php:
<?php
$con = mysql_connect('localhost','user', 'password');
$db = mysql_select_db('my_database');
if($_POST['action'] == 'submit_last_button'){
$previous_variable = mysql_real_escape_string($_POST['previous_variable']);
$last_variable = mysql_real_escape_string($_POST['last_variable']);
$sql = "insert into MyTable (id, variable1, variable2) values ( NULL, '$previous_variable', '$last_variable')";
$query = mysql_query($sql);
if($query){
echo "Record Inserted.";
}else {
echo "Something Wrong!";
}
}
?>
There are various possibilities of what is not working on your code. But first, the problem is not in AJAX not saving on MySQL. AJAX is passing your data to the php script on your server to then, save it on MySQL.
Check if the values are reaching your script correctly;
Check if you're getting a db connection - check error logs or print them out;
Check if you're not getting a SQL syntax erro - again, check for logs;
Check if auto-commit is true (it is by default).

Categories