How to display COUNT() result from mysql to a webpage and automatically update without refreshing webpage? [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have this query:
SELECT COUNT(*) FROM my_table;
And I want to display it in my webpage and automatically update it without refreshing the webpage.
HTML Code:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<h5>/*mysql query result goes here*/</h5>
</div>
</body>
</html>
I also have this count.php:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT COUNT(*) AS Count FROM my_table";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['Count'];
$conn->close();
?>
I don't know how to display the count in my html. I also want to update the display automatically without refreshing the webpage, lets say every 30 seconds.

To do an ajax call to your count.php
$.ajax({
url: "count.php",
cache: false,
success: function(html){
$("#result").html(html);
}
});
Your html file can now contain
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<h5 id="result">/*mysql query result goes here*/</h5>
</div>
</body>
</html>
More information on $.ajax; http://api.jquery.com/jquery.ajax/

you should use post() Methode form jquery with setTimeout().
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<h5 id="count">/*mysql query result goes here*/</h5>
</div>
</body>
<script>
setTimeout(function(){
$.post("Count.php",
{get_count:true},
function(result){
$("#count").html(result);
}
);
},30000);
</script>
</html>
Dont forget to Change the php file. You need to check if POST['get_count'] isst, if you want to handle More then one Post request.

Related

Draw a link from the database and add it to the HTML

I want to make a page where the element will redirect the user to a random page from the database.
I made the HTML code, but I can not deal with PHP and MySQL - I was able to connect to the database, but any attempt to connect the MySQL code with the tag ended in a loss.
Can I count on help writing a PHP script and linking code with ?
<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Montserrat+Subrayada" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">
<title>Random it</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<header></header>
<div class="random">
Random
</div>
<?php
require_once "connect.php";
$conn = #new mysqli($host, $db_user, $db_password, $db_name);
$sql = "SELECT link FROM randomit ORDER BY RAND()";
?>
<footer></footer>
</body>
</html>
Let's try this:
Put this PHP part at the top of the page;
<?php
// set a default link in case something goes wrong
$DEFAULT_LINK = "default.html";
// connect to DB
require_once "connect.php";
$conn = new mysqli($host, $db_user, $db_password, $db_name);
// set query -> get 1 result only with LIMIT 1
$sql = "SELECT link FROM randomit ORDER BY RAND() LIMIT 1";
$result = mysqli_query($conn, $sql);
if ($result !== false)
$row = mysqli_fetch_assoc($result);
else
$row = false;
// if we have a valid result => use it
// else => use the default
if ($row && isset($row["link"]))
$RANDOM_LINK = $row["link"];
else
$RANDOM_LINK = $DEFAULT_LINK;
?>
And now the HTML part:
<!DOCTYPE html>
<html>
<!-- head part... -->
<body>
<header></header>
<div class="random">
Random
</div>
<footer></footer>
<!-- etc... -->

connection php and postgreSQL

I'm have a problem. I want connect PHP and PostgreSQL, but don't know how.
HTML:
<?php
?>
<!DOCTYPE html>
<html lang = "pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Título -->
<title>test</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Font-Awesome CSS -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- Ubicua-cloud CSS -->
</head>
<body>
<form action = "" name = "f1" method = "post" style = "">
<input type = "text" id = "telefone">
<button type = "button" id = "init">iniciar sessão</button>
</form>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="js/bootstrap.min.js"></script>
<!-- Ubicua-cloud-js -->
<script src="login.js"></script>
</body>
</html>
DB connect:
<?php
$connect=pg_connect ("host=localhost dbname=test port=5432 user=postgres password=28974220")or
die("Error");
?>
JS to catch user informations:
$(document).ready(function(){
$('#init').click(function(){
var telefone=$('#telefone').val();
alert(telefone);
$.ajax({
type:"POST",
dataType:'json',
url:'login.Ajax.php',
data:{telefone:telefone},
success: function(response){
if(response.resposta==true){
$('#msg').html(response.msg);
window.location='test.php';
}
else{
$('#msg').html(response.msg);
}
},error:function(){
alert('error');
}
});
});
});
The PHP code to validate informations:
<?php
include_once('includes/connect.php');
$msg_ok=false;
$msg_error='O sistema está indisponível.';
if(isset($_POST['telefone']))
if($_POST['telefone']!="")
$telefone=$_POST['telefone'];
$consulta=pg_query($connect, ("Select * from test where telefone='$telefone"));
if(pg_num_rows($consulta)>0)
$msg_ok=true;
$usua=pg_fetch_array($consulta);
session_start();
$_SESSION['id']=$usua[0];
$_SESSION['telefone']=$usua[1];
$msg_error='Logado';
else
$msg_error='Telefone não existe.';
endif;
else
$msg_error='Telefone incorreto.';
endif
else
$msg_error='Erro.';
endif;
$saidaJson=array('resposta' => $msg_ok, 'msg' => msg_error);
echo json_encode($saidaJson);
?>
I received error messages to catch user informations, help, please.
I'm assuming you are using PDO. If so, you need make changes to the database connection file(substitute the variables with your database values):
<?php
$db = new PDO("pgsql:dbname=$dbname;host=$host";port=$port, $dbuser, $dbpass);
?>
I solved the problem, but now I'm needing exchange informations between the php and js...I have a script that simulates a person typing and need it to talk to users calling them by their proper names, but I don't know how, I need concatenate one variable in JS, but before that I need store one PHP variable in one JS variable.
var init = document.getElementById('init_text');
var init_text = 'Hi <nome>, I'm your friend!';
function digit(str, el) {
var char = str.split('').reverse();
var typer = setInterval(function () {
if (!char.length) return clearInterval(typer);
var next = char.pop();
el.innerHTML += next;
}, 60);
}
digit(init_text, init);

I am not able to set session after login [duplicate]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am not good at this and have been trying but its not working. I don't know why the get.php is index page and its file header.php has another file login.php. I don't know why the session is not working the way I think it should. Footer should show username when logged in but it doesn't.
get.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" media="all">
</head>
<body>
<?php include("header.php");?>
<?php include("menu.php");?>
<?php include("slider.php");?>
<?php include("content.php");?>
<div id="footer">
<?php
if(isset($_SESSION['currentuser'])==true)
{
echo"$username";
}
else
{
echo" not logged in ";
}
?>
</div>
</body>
</html>
login.php
<?php
session_start();
include("connect.php");
if(isset($_POST['login']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from user where username='$username' AND password='$password'";
$run=mysql_query($query);
if(mysql_num_rows($run)>0)
{
$_SESSION['currentuser']=true;
header("Location:get.php");
}
else
{
header("Location:get.php#loginfail");
}
}
?>
Try this:
if(isset($_SESSION['currentuser']) && $_SESSION['currentuser'] == true)
Also remember to include session_start() on each page which requires sessions.
Sessions can only be accessed after a page refresh when they are set. You'll need to reload the page to be able to access the session variables.
Another note: Everywhere you want you use any kind of session, you'll need to start the session with:
session_start();
So your get.php file would look something like this:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" media="all">
</head>
.....etc

php session not working for popup login [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am not good at this and have been trying but its not working. I don't know why the get.php is index page and its file header.php has another file login.php. I don't know why the session is not working the way I think it should. Footer should show username when logged in but it doesn't.
get.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" media="all">
</head>
<body>
<?php include("header.php");?>
<?php include("menu.php");?>
<?php include("slider.php");?>
<?php include("content.php");?>
<div id="footer">
<?php
if(isset($_SESSION['currentuser'])==true)
{
echo"$username";
}
else
{
echo" not logged in ";
}
?>
</div>
</body>
</html>
login.php
<?php
session_start();
include("connect.php");
if(isset($_POST['login']))
{
$username=$_POST['username'];
$password=$_POST['password'];
$query="select * from user where username='$username' AND password='$password'";
$run=mysql_query($query);
if(mysql_num_rows($run)>0)
{
$_SESSION['currentuser']=true;
header("Location:get.php");
}
else
{
header("Location:get.php#loginfail");
}
}
?>
Try this:
if(isset($_SESSION['currentuser']) && $_SESSION['currentuser'] == true)
Also remember to include session_start() on each page which requires sessions.
Sessions can only be accessed after a page refresh when they are set. You'll need to reload the page to be able to access the session variables.
Another note: Everywhere you want you use any kind of session, you'll need to start the session with:
session_start();
So your get.php file would look something like this:
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" media="all">
</head>
.....etc

Trying to get a PHP button to delete MySQL rows

EDIT: Added the whole code for viewProblems, with the actual credential information just ***.
I've been trying to do this all day and I can't figure it out. What I want is a button at the end of each row (the button shows up correctly) that allows me to delete that row from the MySQL database and the page (doesn't delete anything though). The code I have is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<meta name="author" content="">
<title>View Problems</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="well">
<div class="container">
<div class="page-header">
<h1>Jimmy's Laundry</h1>
</div>
<ol class="breadcrumb">
<li>Home</li>
<li>Login</li>
<li>Admin page</li>
</ol>
</div>
</div>
<?php
$servername = "***";
$username = "***";
$password = "***";
$dbname = "***";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT problem_id, machine_id, description FROM tbl_problem";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo '<table class="table table-hover"><tr><th>Problem ID</th><th>Machine Number</th><th>Problem Description</th><th> </th></tr>';
while($row = $result->fetch_assoc())
{
echo "<tr><td>" . $row['problem_id']. "</td><td>" . $row['machine_id']. "</td><td>" . $row['description']. "</td><td><form action='deleteProblem.php?name=" . $row['problem_id']."' method= 'post'><input type='hidden' name='id' value=".$row['problem_id']."><input class ='btn btn-danger' type='submit' name='submit' value='Resolved?'></form></td></tr>";
}
echo "</table>";
}
else
{
echo "There are no problems! :)";
}
?>
</table>
</body>
For my main page, viewProblems.php. My deleteProblem.php page is as follows:
<?php
$query= "DELETE FROM tbl_problem WHERE problem_id={$_POST['id']}";
mysql_query ($query);
if (mysql_affected_rows() == 1)
{
echo "<strong>Row has been deleted</strong>"
}
else
{
echo "<strong>Deletion Failed</strong>"
}?>
I've been browsing this site and Google, and I'm trying to get it to work, but it just won't. The page loads the table correctly, but when I click the button, it takes me from website/viewProblems.php to website/deleteProblem.php?name=9(or 10, 11, 12, 13, depending on which button I press) but the page is just white space and the database doesn't get updated.
Any help would be appreciated.
P.S. I know that mySQL_ methods are dated, but we have to use them.
The script that deletes the row is a separate script that is executed in a separate request. Therefor, it is completely isolated from the request that generated the page and you will have to make a new database connection if you want to query or delete data.
In your current situation, you don't make a connection, so that's why the delete statement fails.

Categories