how to make the result appear in popup widow? - javascript

I want to make the result comes out in a popup window.
Code:
<?php
$con=mysqli_connect("localhost","root","1234","fyp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT password FROM admin WHERE email = '$_POST[email]' AND Admin = '$_POST[admin]'");
while($row = mysqli_fetch_array($result))
echo "your password is : " . " $row['password']" ;
mysqli_close($con);
?>
Is it possible to make it echoed in popup window like javascript alert messages ??
I have tried this but still not working
echo "<script> alert ("<?php echo 'your password is: ' . '$row['password']'?>")</script>";

I found a maybe strange solution for this a while back.
echo "<style onload=\"jsfunc($row['password']);\"></style>";
//in your html or javascript add this function
<script type='text/javascript'>
function jsfunc(data){
alert(data);
}
</script>
the style tag is invisible and will run the function onload, so when its gets echoed. Also I use the style tag because its one of the few tags where the onload works when you echo it like this.
Its a strange solution but it works.

There are some serious flaws in your code, including it being open to SQL Injection. I'd recommend changing it to look more like this:
$con = new MySQLi("localhost","root","1234","fyp");
if($con->connect_errorno) {
echo "Failed to connect to MySQL: ".$sql->connect_error;
}
$email = $sql->real_escape_string($_POST['email']);
$admin = $sql->real_escape_string($_POST['admin']);
$query = "SELECT password FROM admin WHERE email = '$email' AND Admin = '$admin'";
$result = $sql->query($query);
if($result) {
$row = mysqli_fetch_assoc($result);
$pass = $row['password'];
echo '<script> alert("Your password is '.$pass.'");</script>';
} else {
//do some error handling
}
//the closing of a mysqli connection is not required but
mysqli_close($con);
Real escape string is not 100% proof against injection but is a good place to start with sanitising your inputs. Additionally I would strongly advise against storing your passwords in plain text. Please take a look at the PHP sha1() function or the SQL equivalent when storing the passwords initially.

Use this code
<?php
$alert='your password is: '.$row['password'];
?>
<script>
alert("<?php echo $alert; ?>");
</script>
It will work for sure.

Related

i can't put the input data into the database

this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe

Trying to change from alert to popup window [duplicate]

This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
I'm trying to switch the "success/fail" notifications to my webpage. I've been successful doing this in several parts of my test website, but I'm running into a bit of a problem on my login page. My original way of doing this used an alert popup, which works okay, but doesn't provide the style I'm looking for. I decided to use the template that has been working for me in other parts of the website, but the login is unique since it's here where I establish my session for a user.
Here is my original login code which works as intended but uses a generic alert window...
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script> window.location.href='../default.html'; alert('Your credentials could not be validated!')</script>";
}
}
mysqli_close($link);
?>
Here is the code I'm trying to get to work but comes up with
Parse error: syntax error, unexpected end of file on line 38.... which is my ?> to close out the php.
<?php
session_start();
require_once '../php/connect.php';
if (isset($_POST['username']) and isset($_POST['password'])){
$username = mysqli_real_escape_string($link, $_POST['username']);
$password = mysqli_real_escape_string($link, $_POST['password']);
$result = mysqli_query($link, "SELECT * FROM planner WHERE username = '$username' and password = '$password'");
$count = mysqli_num_rows($result);
if ($count !== 1){
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
} else {
$_SESSION['username'] = $username;
}
if (isset($_SESSION['username'])){
header("Location: ../php/main.php");
} else {
echo "<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor='#EFEFEF'/>');
no.document.write('</br>');
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>Your credentials could not be verified</p></br>');
no.document.write('<div style='text-align:center'><button style='width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica' value='Close' onclick='window.close()'>OK</button></div>');
window.location.href = '../default.html';</script>";
}
mysqli_close($link);
?>
I'm pretty sure this has to do with the quotes but I've tried several different combinations and I still get the error.
The window.open code works great on my other pages if I can keep all the if, else statements within the javascript. In these pages I just use the PHP tags to grab the parameters outside the javascript where needed.
However when I attempt to do with this with the $_Session, it doesn't work.
If this is a quotes problem, I'd appreciate it if someone could point me in the right direction. If this is related to the session, I could use some help formatting the javascript so I call the ?_Session properly.
There are so many quote issues with your code, try to put script separately or use heredoc, nowdoc.
PHP can read multiple lines with heredoc/nowdoc.
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
Use delimiters and indentation correctly and you can put actual JS code in between.
Example as per your use case.
echo <<<SCRIPT
<script>
var no = window.open('', 'failure','top=250,left=500,height=200,width=350,menubar=no,scrollbars=no,toolbar=no');
no.document.write('<body bgcolor="#EFEFEF"/>');
no.document.write('</br>');
no.document.write('<p style="text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px">Your credentials could not be verified</p></br>');
no.document.write('<div style="text-align:center"><button style="width:100px;border-style:solid;border-width:5px;border-color:#003399;position:absolute;left:35%;background-color:#003399;color:#ffcc00;font-weight:bold;font-family:Helvetica" value="Close" onclick="window.close()"">OK</button></div>');
window.location.href = '../default.html';
</script>
SCRIPT;
Remember you can not use same kind of quote in between without escaping properly but you can also double between single and vice-versa.
I think your problem is using ' inside another '
no.document.write('<p style='text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px'>...
You need to escape this char like this:
no.document.write('<p style=\'text-align:center;color:white;background-color:red;font-family:Helvetica;font-size:20px\'>...

How to display an alert box in php?

I want to display an alert box showing a message with PHP. If I not use alert box I get the right answer such "update subject set semester=2 where id=171 ". But after I change into alert box the answer i get in the alert box only "update subject set $f=$data where id=$did" and it does not update in database.
Here is my PHP code:
if ($tag == 2) {
$query = '<script type=text/javascript> alert("update subject set $f=$data where id=$did")</script>';
$result = mysql_query($query);
print "$query";
}
Change the quotations. Learn the difference between single and double quotes. Also, you can't update using that which is an invalid query with Javascript statement. Instead use:
if ($tag == 2) {
$query = "update subject set $f=$data where id=$did";
$result = mysql_query($query);
echo "<script type=text/javascript>alert('$query')</script>";
}
Note : mysql_ extensions are deprecated, use mysqli or PDO
What you are passing to the deprecated mysql_query function was not valid sql and would cause an error, I suspect you were trying something along these lines?
if ($tag == 2) {
$sql="update `subject` set `$f`='$data' where `id`='$did'";
$query = '<script type=text/javascript> alert('$sql')</script>';
$result = mysql_query($sql);
echo $query;
}
If you want a success message you should do:
if ($tag == 2) {
$query = 'update subject set $f=$data where id=$did")';
$result = mysql_query($query);
if($result)
echo "<script type=text/javascript> alert('message')</script>";
}
}

How to auto-save and auto-update textarea

I'm currently attempting to create a test-website based on the "Secret Diary" project of a web developer course. I'm trying to create a page that saves all of the notes written into a textbox, and displays them when I log in again. Almost everything works - I can start a session and display the saved text when I log in, but the box is deleting the textbox's saved data when the page is loaded. I know that there are better ways of storing the info, I'm just looking for how to get this method to work. This should be all of the relevant code:
mainpage.php:
<?php include("updatediary.php"); ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form method="post">
<textarea class="form-control"><?php echo $diary; ?></textarea>
</form>
<script>
$("textarea").keyup(function() {
$.post("updatediary.php", function(){diaryInput:($("textarea").val());} );
});
</script>
updatediary.php:
<?php
include("connection.php");
$query = "SELECT content FROM users WHERE id='".$_SESSION['id']."' LIMIT 1";
$result = mysqli_query($dbCon,$query);
$row = mysqli_fetch_array($result);
$diary = $row['content'];
if ($_POST['diaryInput']!="") {
$updateQuery = "UPDATE `users` SET `content`='".mysqli_real_escape_string($dbCon, $_POST['diaryInput'])."' WHERE id='".$_SESSION['id']."' LIMIT 1";
if (mysqli_query($dbCon, $updateQuery)) {
echo "saved";
} else {
echo "not saved";
};
}
?>
connection.php:
$dbCon = mysqli_connect("localhost", "owenxwfg_admin", "(password)", "owenxwfg_users");
Any help would be awesome. I personally think that there's a problem with my $.post part.

How to add validation(javascript) in php?

let say that, i want to my change password in php code then it will validate by the use of javascript. before it return to my index page or it will popup on index page. how can i do it? any trick that you can suggest? :)
<?php
include('config2.php');
error_reporting(E_ERROR | E_PARSE);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$val = $_GET['val1'];
session_start();
$ak = $_SESSION['autokey'];
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
header("location:index");
?>
thanks in advance :)
You could change your code block like this..
$sql = "UPDATE tbl_user SET password = '". md5($val) ."' WHERE autokey = '$ak'";
mysql_query($sql);
if(mysql_affected_rows())
{
echo "<script>alert('Password was successfully changed !');</script>";
echo "<script>window.location='index.php'</script>";
} else
{
echo "<script>alert('Password was not changed');</script>";
echo "<script>window.location='index.php'</script>";
}
As the comment says.. You are mixing up mysql_* and mysqli_*. Change that first.
Sidenote: Switching to PreparedStatements is even more better to ward off SQL Injection attacks !

Categories

Resources