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.
Related
I'm making a movie rating website for a project and how to do the rating system has left me at a blank. Please let me know of a proper way to this if you know.
This gets the movie number from the url and displays the relevant information in the page
<body>
<?php
global $conn;
$conn = mysqli_connect('localhost','root','','filmsdb');
function show()
{
global $film;
global $conn;
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
?>
//displays the movie information and uses radio buttons to get user rating
Then this lets the user rate the movie
<?php
}
function act1()
{
if(isset($_POST['rsub']))
{
global $film;
global $conn;
$rate = $_POST['rate'];
$sqlr= "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn,$sqlr);
}
if($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored ';
echo mysqli_error($conn);
}
}
$conn = null;
?>
</body>
</html>
when only the first function is being used, it works, but when I try to use the rating system, this error comes in the browser, mysqli_query() expects parameter 1 to be mysqli, null given... Any idea on a workaround for this?
Your issue is that the two variables you're relying on with the DB connection, $conn and $film, do not exist when the page has posted back the user rating data.
Your application's lifecycle goes like this:
1) User makes initial request. PHP starts and runs the first code block, it echoes some values to the page, page is returned to the user. Once the page is returned, the request is complete and PHP stops executing. All variables declared and in memory are lost because the process has stopped running.
2) The page returned from the PHP script arrives in the user's browser. User enters their rating and posts the data back to the server. This constitutes an entirely new request.
3) The new request arrives at the server. PHP starts up again. The web is inherently stateless, so by default it remembers nothing of the previous request. Certainly not the names or values in any in-memory variables - the process that contained them died long ago and has no association with the new one.
Therefore, if you have any values that you need to use again in PHP for the second request, you can either create them again, or receive them in the request data, or the first PHP script must have stored them somewhere persistent that you can retrieve them from, such as a session variable or cookie, or database.
It's not clear from your posted code, but presumably in the second request the function act1() gets called somehow and tries to insert the data into the database. It fails because neither $film or $conn have any values in them in this new request.
I suggest you solve it like this:
1) Create your connection object again, this is easy, and you need to re-connect to MySQL for this request anyway.
2) the film you're rating should be passed back from the browser in the form data.
This is the first script, to get the initial film data and render the ratings form to the page.
//re-usable function to connect to DB. Maybe move this out to a separate file so all pages can use it.
function getDBConn() {
return mysqli_connect('localhost','root','','filmsdb');
}
function show()
{
$conn = getDBConn();
$film = $_GET['fm'];
$sql = "SELECT * FROM movies WHERE m_No='$film'";
$ok = mysqli_query($conn,$sql);
$data = mysqli_fetch_array($ok);
$c_r= $data[8];
$c_rc= $data[9];
$conn = null;
}
Your latest update doesn't show the form but I'm going to assume it's something like this, with an additional film hidden field. There should be suitable form tags around it as well.
<input type="radio" value="1" name="rate">
<input type="radio" value="2" name="rate">
<input type="radio" value="3" name="rate">
<input type="radio" value="4" name="rate"><input type="radio" value="5" name="rate">
<input type="hidden" name="film" value="<?php echo $film;?>"/>
<input type="submit" value="Rate" name="rsub">
Now is the second script, to be run when the rating data is submitted. You haven't shown how act1() is called but I'll assume you've got that covered.
function act1()
{
if(isset($_POST['rsub']))
{
$film = $_POST['film']; //get the film ID from the submitted form
$conn = getDBConn(); //assuming this script is in the same .php file as the first block, otherwise you'll need to move getDBConn into a separate php file and then include the file in each script.
$rate = $_POST['rate'];
$sqlr = "UPDATE movies SET rating=rating+$rate, rate_count=rate_count+1 WHERE m_No='$film'";
$output = mysqli_query($conn, $sqlr);
}
if ($output==1)
{
echo 'Data Stored';
}
else
{
echo 'Data Not Stored';
echo mysqli_error($conn);
}
$conn = null;
}
P.S. I know it's just an example project, but if you make a real-life site please heed the comments above re SQL injection, and don't let your applications and websites log into your DB as "root" either - give them only the privileges they actually need.
I am very new to SQL and to say the least, I am struggling.
My table looks like this:
All I want to do is be able to increment any of these values by one upon the press of a button, like this:
This is how it looks on the website, but nothing is functional at all yet.
I have an understanding of HTML, CSS, and PHP, so if I were to know the correct way to do this with SQL, I should be able to implement it.
Thanks.
Ok, I see people suggesting AJAX ("elsewhere" as well as here), but you are unfamiliar with this. I'm going to suggest a completely non-Javascript solution, sticking with HTML, PHP, and MySQL, as you already know these. I would definitely recommend learning Javascript at some point though.
I've no idea of your level of understanding, so please let me know any bits of the following code you don't follow, and i'll explain in more detail.
<?php
/* Initialise the database connection */
$db = new mysqli("localhost", "username", "password", "database");
if ($db->connect_errno) {
exit("Failed to connect to the database");
}
/* First, check if a "name" field has been submitted via POST, and verify it
* matches one of your names. This second part is important, this
* will end up in an SQL query and you should NEVER allow any unchecked
* values to end up in an SQL query.
*/
$names = array("Anawhata","Karekare","Muriwai","Piha","Whatipu");
if(isset($_POST['name']) && in_array($_POST['name'], $names)) {
$name = $_POST['name'];
/* Add 1 to the counter of the person whose name was submitted via POST */
$result = $db->query("UPDATE your_table SET counter = counter+1 WHERE name = $name");
if(!$result) {
exit("Failed to update counter for $name.");
}
}
?>
<table>
<?php
/* Get the counters from the database and loop through them */
$result = $db->query("SELECT name, counter FROM your_table");
while($row = $result->fetch_assoc()) {
?>
<tr>
<td>
<p><?php echo $row['name'];?></p>
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="hidden" name="name" value="<?php echo $row['name']; ?>" />
<input type="submit" name="submit" value="Add One" />
</form>
</td>
<td><?php echo $row['counter']; ?></td>
</tr>
<?php
} // End of "while" each database record
?>
</table>
One way is to use AJAX on sending the form to make calls to a php script that handles the mysql query and "adds one". You should put a hidden input with the name of the person you want to increment. That's if you don't want to refresh the page.
If you don't mind refreshing, make every button part of a form, and send to the same php file.
I recently came across a library, called meteor.js that is capable of doing all this. I have not yes tested it, though.
I want to use one single page with pre-defined divs, layout etc. as basis so that when a product is clicked on from elsewhere it loads that product info onto the page?
They way im doing it ill be sitting here till about 2020 still typing out product info onto pages.
EDIT*************
function product ()
{
$get = mysql_query ("SELECT id, name, description, price, imgcover FROM products WHERE size ='11'");
if (mysql_num_rows($get) == FALSE)
{
echo " There are no products to be displayed!";
}
else
{
while ($get_row = mysql_fetch_assoc($get))
{
echo "<div id='productbox'><a href=product1.php>".$get_row['name'].'<br />
'.$get_row['price']. '<br />
' .$get_row['description']. '<br />
' .$get_row['imgcover']. "</a></div>" ;
}
}
}
In addition one problem I have with that code is that the <a href> tag only goes to product1.php. Any ideas how I can make that link to blank product layout page that would be filled with the product info that the user has just clicked on, basically linking to itself on a blank layout page.
Thanks any help would be great!
Thanks Maxyy
Since you dont have code this is a general way of doing this. What you want is a template for the product page
Query the database
load the data into a variable
make a script that will print out the data from the variable into a product page
somescript.php
<?php
$productid = $_REQUEST['productid']; //Of course do sanitation
//before using get,post variables
//though you should be using mysqli_* functions as mysql_* are depreciated
$result = mysql_query("select * from sometable where id='{$productid}");
$product = mysql_fetch_object($result);
include("productpage.php");
productpage.php
<div class="Product">
<div class="picture"><img src="<?php echo $product->imghref;?>" /></div>
<div class="price"><?php echo $product->price;?></div>
</div>
so on and so fourth. Included scripts use whatever variables are currently in the scope of the calling function
If you are meaning to load the products into the same page without doing another page load you will need to use ajax. Which is javascript code that use XHR requests to return data from a server. You can either do pure javascript or a library like jQuery to simplify the process of doing a xhr request by using $.ajax calls.
I know this question has been asked over 4 years ago, but since there's been no answer marked as right, I thought I might chip in.
First, let's upgrade from mysql and use mysqli - my personal favorite, you can also use PDO. Have you tried using $_GET to pull the id of whatever product you want to see and then displaying them all together or one at a time?
It could look something like this:
<?php // start by creating $mysqli connection
$host = "localhost";
$user = "username";
$pass = "password";
$db_name = "database";
$mysqli = new mysqli($host, $user, $pass, $db_name);
if($mysqli->connect_error)
{
die("Having some trouble pulling data");
exit();
}
Assuming the connection was made successfully we move on to checking for an ID being set. In this case I check it via an URL param assumed to be id. You can make it more complex, or take a different approach here.
if(isset($_GET['id']))
{
$id = htmlentities($_GET['id']);
$query = "SELECT * FROM table WHERE id = " . $id;
}
else
{
// if no ID is set, just bring all the results down
// then you can modify how, and which table the results
// are being used.
$query = "SELECT * FROM table ORDER BY id"; // the query can be changed to whatever you would be prefer
}
Once we have decided on a query we go on to start querying the database for information. I have three steps:
Check query >
Check table for records >
Loop through roles and create an object for each.
if($result = $mysqli->query($query))
{
if($result->num_rows > 0)
{
while ($row = $result->fetch_object())
{
// you can set up your element here
// you can set it up in whatever way you want
// to see your product being displayed, by simply
// using $row->column_name
// each column becomes an object here. So your id
// column would be pulled using $row->id
echo "<h1>" . $row->name . "</h1>";
echo "<p>" . $row->description . "</p>";
echo "<img src=" . $row->image_path . ">";
// etc ...
}
}
else
{
// if no records match the selected ID
echo "Nothing to see here...";
}
}
else
{
// if there's a problem with the query
echo "A slight problem with your query.";
}
$mysqli->close(); // close connection for safety
?>
I hope this answers your question and can help you if you are still stuck on this problem. This is the bare skeleton of what you can do with MySQLi and PHP, you could always use some Ajax to make the page more interactive, and user-friendly.
Adding content to a page on click needs to be done in either Javascript or in JQuery.
You can use ajax call to retrive the needed data from php page, Syntax is here.
Or you can also load a php page to a div content with .load() function in JQuery, Syntax is here.
Is it possible to refresh a divs content only if new content is added to the database?
I'm using this for "recent posts" that appear in the side menu.
Right now the div is set refresh every 10 seconds.
Is it somehow possible to check it a new post was added to the db and then add only that posts data to the div?
I'm using MySql, php and jquery to do all of this.
Yes, you can do it by comparing the text content.
function updateHtmlContent() {
var htmlContent=$('#divToUpdate').text();
$.ajax({
type: "GET",
datatype: "text",
//php function that should give you the text back
url: 'dataBaseFunction.php',
success: function(data) {
if (htmlContent != data) {
$('#divToUpdate').text(data);
}
}
});
}
//compare and upate every 20 seconds
setInterval(updateHtmlContent(), 20000);
Hope this help!
YES IT IS POSSIBLE
The below code will get the recent photos that has been added:
AFTER THE TIMER.PHP WAS LAODED (or your wordpress blog page)
AND ONLY AFTER A NEW PHOTO IS ADDED (you can use it for recent posts, comments, or anything)
This can be used to create a live blog for example, where the user will see all the recent comments, images or posts, or everything, even if he doesn't reload the current page. And it won't consume a lot of bandwidth as the content will be reloaded ONLY IF THERE IS NEW ADDED (it will only send a tiny check in the database otherwise).
I've just finished working out a solution for that, and I have to share it with you. I was doing it for Wordpress, i needed a function that gets the photos that has been added ONLY after the user loaded the page. It could be done by simply refreshing the div every 5 seconds, but imagine if there were 20 photos, and they had to be refreshed every 5 seconds... that's a lot of MB of data. So we will refresh them ONLY when a new photo is added (you can apply it to anything, from posts to comments or users, etc.).
There are 3 PHP files: timer.php, check.php and display.php.
The timer.php will load the check.php every 5 seconds, to check if new content is added. Notice the -6 extraction from the time of the current load of check.php.
The date-time of the timer.php will be passed (by check.php?tim=**print date) through the check.php (by **display.php?timm='. $tizz .') and to the display.php, so we can use it for a reference in our database (that will be the time from where we will load all the images, if new images are added).
If any questions, just ask. It has to work for you too, as it works for me.
ENJOY! :)
Below are the 3 PHP files, just customize them for your needs:
THE TIMER.PHP (or your wordpress blog pages):
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setInterval(function(){
$("#quotex a").load("check.php?tim=<?php print date("Y-m-d H:i:s"); ?>");
}, 5000);
});
</script>
<div id="quote"><a></a></div>
<div id="quotex"><a></a></div>
THE CHECK.PHP :
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' ORDER BY `wp_posts`.`id` DESC LIMIT 1";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
$atime = $row['post_date'];
$tizz = $_GET['tim'];
$dsff = $row['post_date'];;
$duff = date("Y-m-d H:i:s");
//convert the date-time into seconds so we can extract 6 seconds from it
$six = strtotime(date("Y-m-d H:i:s"))-6;
//convert the latest image date-time too from database so we can compare it
$sox = strtotime("$dsff");
if ($six < $sox)
{
echo '<script type="text/javascript">$(document).ready( function(){ $("#quote a").load("display.php?timm='. $tizz .'"); } ); </script>';
}
}
// Close the database connection
mysql_close();
?>
THE DISPLAY.PHP:
<?php
$tipp = $_GET["timm"];
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database name") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM wp_posts WHERE post_mime_type LIKE 'image/jpeg' AND post_date > '$tipp' ORDER BY `wp_posts`.`id` DESC LIMIT 10";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
//guid is the column where the image url is located in the wordpress database table
$atime = $row['guid'];
echo "<img src='". $atime ."' /><br />";
}
// Close the database connection
mysql_close();
?>
Yes is possible, but you need to create a method in php and use Ajax to refresh your div.
If you update your question with code I can provide an example.
I think you are probably about 90% of the way there. I assume you are using jQuery to AJAX in the content every 10 seconds (PS That seems like a lot?)
I think you could solve your problem by making the backside function start with posts after the most recent that was found.
So if your query looks like this now:
SELECT a,b,c FROM foo
You should change it to
SELECT a,b,c FROM foo WHERE id > $last_found_id
You can store last_found_id in your Javascript and send it back when you call the function. If your result set is empty then you don't have to refresh the div.
This change will also probably require that you are pre/appending to the div instead of overwriting it completely.
look at the setInterval(function, time) in javascript to make a loop each "time" (in milliseconds),
and the function $.ajax() in jQuery to pass the information to the server..
also, you have to create the new content with .html() or .append()
Have searched for the answer but no joy, so here goes...
I'm working on a mobile hybrid app. I want the user to fill in their id number, which is then submitted to a javascript function for basic validation, then kicks in a jQuery.getJSON request to my serverside PHP which returns the data and then my jQuery will repopulate the form div with the data.
Currently it doesn't really work at all in Firefox, and only works correctly in Safari after I press the submit button for a second time. It returns the correct data, so the link is ok.
My problem is: Why does the div not get repopulated after the first click?
HTML:
<div id="login540div">
<form id="login540form" onSubmit="login540()">
Enter Student ID number<input type="text" name="login540id" id="login540id"/>
<input type="submit" value="Submit" />
</form>
</div>
Javascript:
function login540(){
// validates the data entered is an integer.
var loginNo = document.getElementById("login540id").value;
//if(!isNaN(loginNo))
if((parseFloat(loginNo) == parseInt(loginNo)) && !isNaN(loginNo))
{
//jSonCaller(loginNo);
$.getJSON('http://localhost:8888/c05673160/login540.php?q='+loginNo, function(data){
//alert(data);
$('#login540div').html("<p>First Name ="+
data.firstName+
"</p> Last Name ="+data.lastName+" </p>Module No.1 ="+
data.moduleNo1+"</p> Module No.2 ="+
data.moduleNo2+"<p> Course ID="+
data.courseID+"</p>");
})
}
else
{
// alert(loginNo); CHECKED
alert("Please make sure to insert only a whole number");
}
Then the PHP goes like this...
<?php
include ("config.php");
/*
require_once('FirePHPCore/FirePHP.class.php');
ob_start();
$firephp = FirePHP::getInstance(true);
$var = array('i'=>10, 'j'=>20);
$firephp->log($var, 'Iterators');
*/
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'root';
$dbname = 'collegeData';
$q=$_GET["q"];
$table = "studentTable";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$conn)
die('Could not connect: ' . mysql_error());
if (!mysql_select_db($dbname))
die("Can't select database");
$result = mysql_query("SELECT * FROM {$table} WHERE studentID = '".$q."'");
if (!$result)
die("Query to show fields from table failed!" . mysql_error());
$json = array();
while($row = mysql_fetch_array ($result))
{
$json = array(
'firstName' => $row['firstName'],
'lastName' => $row['lastName'],
'moduleNo1' => $row['moduleNo1'],
'moduleNo2' => $row['moduleNo2'],
'courseID' => $row['courseID']
);
}
$jsonstring = json_encode($json);
echo $jsonstring;
mysql_close($conn);
?>
I can't figure out what's wrong, and I've been messing around with various things for the last few days trying to fix it, but no joy, so I'd really appreciate any help you can give.
#Robbie had a good point that you don't appear to be stopping the default behavior of the form submission. To do this you need to change a couple things:
onSubmit="login540()" needs to change to onSubmit="return login540()" otherwise whatever you return from the login540() function will be ignored.
At the end of the login540() function you need to return false; to stop the form from submitting normally. You can also pass in the event object as the first argument and use event.preventDefault() instead: function login540(event){event.preventDefault();...}.
To do yourself a favor however, you can use jQuery to bind the submit event handler to the form rather than using inline JS (tisk, tisk, :) )
$('#login540form').on('submit', login540);
This way you can keep all of your JS in one place rather than spread-out all over your HTML.
The bottom of Function login540() is missing, but this needs to kill the default "submit" action: this can be done with "return false;" at the end. As I can't see the end, not sure if this happens or not, but the form probably "submits" while the AJAX is running.
This is compounded as the form doesn't have an action, which probably explains the different browser behaviour. I suggest setting action to "#" and then, if you see "#" added in the URL then the form has submitted and not been stopped by your function.