How to add validation(javascript) in php? - javascript

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 !

Related

Export data from php to html webpage

Still new to this topic, I was wondering if there was a way for me to export data from php into a html webpage. In this particular case I'm trying to make it so that the system can check the data when an already registered user logs in and compares them with the user's input. The problem is I don't know how to take the user's data saved in the database (In this case $row) when the header switches into the next html webpage to be used.
<?php
$Email = $_POST['Ema'];
$Contraseña = $_POST['Cont'];
if(empty($Email) || empty($Contraseña)){
echo ("Hablamos1");
exit();
}
mysql_connect('localhost','root','password') or die("Error al conectar " .
mysql_error());
mysql_select_db('isoft') or die ("Error al seleccionar la Base de datos: " .
mysql_error());
$result = mysql_query("SELECT * from usuarios where Email='" . $Email . "'");
if($row = mysql_fetch_array($result)){
if($row['Contraseña'] == $Contraseña) {
session_start();
header("Location: prueba.php");
}else{
echo("Hablamos");
exit();
}
}else{
echo("hablamos")
exit();
}
?>
You can re-run the SQL on the new page (ex. prueba.php), or pass them as parameters to the URL you are redirecting to:
header("Location: prueba.php?record_id=" . urlencode($row['id']));

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

PHP echo selected value from html dropdown list

In my dropdown list, i put all the "pack_name(s)" the user has posted and I display it all in the list for the user to select and update. So when the user selects one and hits submit, i want to get that "value" submitted and use it for later purposes but ive been researching and only found "pre-set" values with html and the value was given using Jquery. So i wondering if its possible to basically take the "pack_name" selected and when the user hits submit, echo out the selected value.
PHP
<?php
session_start();
if(empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == 'post'){ //catch file overload error...
$postMax = ini_get('post_max_size'); //grab the size limits...
echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!</p>"; // echo out error and solutions...
return $postMax;
}
if(isset($_COOKIE['id'])){
if($_SESSION['came_from_upload'] != true){
setcookie("id", "", time() - 60*60);
$_COOKIE['id'] = "";
header("Location: developerLogin.php");
exit;
}
try{
// new php data object
$handler = new PDO('mysql:host=127.0.0.1;dbname=magicserver', 'root', '');
//ATTR_ERRMODE set to exception
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die("There was an error connecting to the database");
}
$userid = $_SESSION['id'];
$stmt = $handler->prepare("SELECT * FROM pack_profile WHERE pack_developer_id = :userid");
$stmt->bindParam(':userid', $userid, PDO::PARAM_INT);
$stmt->execute();
echo "<select>";
while($result = $stmt->fetch()){
echo "<option>" . $result['pack_name'] ."</option>";
}
echo "</select>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
$token = $_SESSION['token'];
}
}
?>
You need to give the select element a name attribute, and give each option element a value attribute.
For example:
echo "<select name=\"pack\">";
while($result = $stmt->fetch()){
echo "<option value=\"" . $result['pack_name'] . "\">" . $result['pack_name'] ."</option>";
}
echo "</select>";
Of course you should be escaping anything which could contain &, < or " with something like htmlspecialchars().

How to display the body of the mail in another page if clicked on the subject

So I am creating an inbox in PHP and It displays Mail Id and Subject.
If you click that division(containing mail id and subject), it opens up a new page, read. PHP where the body and attachments are displayed.
I am facing some problem in getting to know which division is being clicked and how to display the mail of that particular person.
My concerned code is:
<?php
$conn = connect(); //Connects to the database
$sql = "select senderId, subject, body, attachment from mail where receiverId = '".$_SESSION["Email"]."' ";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='mail' onclick='location.href=`read.php`;'>";
echo $row["senderId"] . " - " . $row["subject"];
echo "</div>";
echo "<hr />";
}
$conn->close();
?>
I have an idea of storing the variables using SESSION as:
if (isset($_GET['div'])) {
$_SESSION["body"] = $row["body"];
$_SESSION["attachment"] = $row["attachment"];
}
But where do I place the latter part of the code and suggest me if I can make an modifications please.
You can echo out the id during the while loop iteration.
echo "<div class='mail' onclick='location.href=`read.php?id=". $row['id'] ."`;'>";
And inside the read.php file, you can then grab that value by using $_GET['id'].

how to make the result appear in popup widow?

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.

Categories

Resources