i was coding a delete function called deleteProgram() inside a class and everything is working fine but i want to add some javascript code.
<?php
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
$result = $this->connect()->query($sql);
header("Location: ../php/program.php");
exit();
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
So, this is what i did. I created a try/catch inside my deleteProgram() function inside the if statement and there i use an echo to run the javascript code. But it didn't display anything so that is where got stuck.
<?php
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
try{
$result = $this->connect()->query($sql);
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal("Deleted Successfully!", "Program has been deleted", "success");</script>';
header("Location: ../php/program.php");
exit();
}catch(PDOException $e){
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal ( "Delete failed!" , "'.$e->getMessage().'" , "error" );</script>';
exit();
}
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
As suggested in comments, your code is open to SQL injections, try using parameterized prepared statements instead.
The header() function is redirecting the user before the page is loaded, so the script is written but never shown as the new page is now loaded right after.
One solution is to use the $_SESSION. It can go like this:
On your DeleteProgram class PHP file:
# [...]
session_start();
# [...]
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
try{
$result = $this->connect()->query($sql);
echo '<style>.swal-text{
text-align: center;
}</style>';
$_SESSION['swal'] = [
'title' => "Deleted Successfully!",
'message' => "Program has been deleted",
'status' => "success"
];
header("Location: ../php/program.php");
exit();
}catch(PDOException $e){
# [...]
}
}
# [...]
In the ../php/program.php file (somewhere in the <body>):
# [...]
session_start();
# [...]
<?php if(isset($_SESSION['swal'])) {
$title = $_SESSION['swal']['title'];
$message = $_SESSION['swal']['message'];
$status = $_SESSION['swal']['status'];
echo "<script>swal($title, $message, $status);</script>";
} ?>
May I also suggest you to not put CSS style in your code like that. It's not very reliable on where its gonna be written. As your swal() function requires you to place a <script> tag to be used, consider placing you <style> tag next to it or so.
Related
I new in programming. Currently, I develop a system that registration part. The registration part is successfully saved to the database. What I want to know is how to popup an alert dialog with one button e.g "Ok" after registration was successful and redirect to another page, such as home page. Now I only echo "successfully saved"
Below is my current code
<?php
require "DbConnect.php";
$name = $_POST['name'];
$badgeid = $_POST['badgeid'];
$position = $_POST['position'];
$department = $_POST['department'];
$factory = $_POST['factory'];
$reviewer = $_POST['reviewer'];
$title = $_POST['title'];
$year = $_POST['year'];
$month = $_POST['month'];
$suggestionwill = $_POST['suggestionwill'];
$present = $_POST['present'];
$details = $_POST['details'];
$benefit = $_POST['benefit'];
$sql_query = "INSERT INTO topsuggest (name,badgeid,position,department,factory,
reviewer,title,year,month,suggestionwill,present,details,benefit) VALUES('$name','$badgeid','$position','$department','$factory','$reviewer','$title','$year','$month','$suggestionwill','$present','$details','$benefit')";
if(mysqli_query($conn,$sql_query))
{
echo "<p id='msg'></p>";
}
else
{
echo "Error!! Not Saved".mysqli_error($con);
}
?>
Just use php header and use javascript to alert a message .
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: PATH TO BE REDIRECTED');
}
For a example
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: ../Insert/Index.php');
}
Please note that space between Location: is compulsory
After inserting data you can simply redirect to your interested page with a success message like:
header("location:page_of_interest.php?msg=Record Inserted");
and on page_of_interest.php you can simply check for msg and show if it is set like:
if(isset($_GET['msg'])){
echo $_GET['msg'];
}
I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.
DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>
Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.
Well For Start I Want To Tank You All For The Help
The Script now it create a table but send empty info
so i have try to do like this:
http://mediaads.eu/villageop/back/savepoints.php?user_id=abcdefghijklm
Now The script wen i call it give me this error:
So I Have Edit The Script code to clean it
so now my code is:
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
$servername = "localhost";
$username = "publiadd_publix";
$password = "1a3g7893fsh";
try {
$conn = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_GET['user_id'])){
//$user_id = intval($_GET['user_id']);
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
try {
$dbh = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
$user_id = #$_GET['user_id'];
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (user_id) VALUES ('".$_POST["user_id"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
$sql->execute(array($user_Id));
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your ID was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your id wasnt passed in the request.';
}
// close MySQL connection
$conn = null;
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
The method you are using in your forms is GET so use $_GET not $_POST as it goes in your if condition. So replace $_POST with $_GET and second error is your table name it is users table not publiadd_registervillageop so your sql query looks like,
$sql = "INSERT INTO users (user_id) VALUES ('".$_GET["user_id"]."')";
I am trying to send an array from php (that I have taken from a mysql table to js). Although there a lot of examples out there I can't seem to make any of them work. The code that I have reached so far is:
php_side.php
<!DOCTYPE html>
<html>
<body>
<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
/*while($row = mysqli_fetch_array($result)) {
echo $row['User1_number'];
echo "<br/>";
echo $row['User2_number'];
echo "<br/>";
echo $row['canvas_channel'];
echo "<br/>";
}*/
echo json_encode($result);
mysqli_close($con);
?>
</body>
</html>
test_ajax.html
$(document).ready(function(){
$.getJSON('php_side.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
This is my first app that I use something like this, so please be a little patient.
Right now you're sending the complete page markup mixed with your json response, which of course will not work.
For example imagine that you have the following php script which suppose to return a json response:
<div><?php print json_encode(array('domain' => 'example.com')); ?></div>
The response from this page would not be json since it also will return the wrapping div element.
You can move your php code to the top of the page or simply remove all the html:
<?php
// uncomment the following two lines to get see any errors
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
// header can not be called after any output has been done
// notice that you also should use 'application/json' in this case
header("Content-type: application/json");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
// fetch all rows from the result set
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
mysqli_close($con);
echo json_encode($data);
// terminate the script
exit;
?>
I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>