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']));
Related
I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.
echo "<a class='activater' href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'> <span class='glyphicon glyphicon-trash'></span></a>";
It calls the following php Page, which handle the SQL Part:
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($sth)
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
echo sqlsrv_errors();
header("location: ma_QualiOverview.php?message=failed");
}
$connection = null;
Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.
<?php
if($_GET['message']=='success'){
echo '<script language="javascript">';
echo 'alert("Erfolgreich gelöscht.");';
echo '</script>';
} elseif($_GET['message']=='failed'){
echo '<script language="javascript">';
echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
echo '</script>';
}
?>
What do i miss?
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.
Since $sth is always defined, you always get the success result
See the modified code here
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($result )
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
header("location: ma_QualiOverview.php?message=failed");
echo sqlsrv_errors();//Echo must be after header
}
$connection = null;
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.
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 !
I am trying to pass $email field to thank you page which appears after redirection once user submits the enquiry form.
Its a 2 step enquiry form with thank you page being last.
It seems like the SESSION is live on thank you page however the values are lost. I'd like to get $email field posted on the thank you page to an iframe. Please let me know where exactly the session id is going wrong?
Here are the codes:
Step 1: Small Enquiry form
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
if(isset($_REQUEST['btnSubmit']) == 'Next'){
$obj = new validation();
$obj->add_fields(trim($_POST['txt_fname']), 'req', 'Enter your first name.');
$obj->add_fields(trim($_POST['txt_contact']), 'req', 'Enter phone number.');
$obj->add_fields(trim($_POST['txt_finamount']), 'req', 'Enter the amount.');
$obj->add_fields(trim($_POST['sel_loantype']), 'req', 'Please select vehicle type.');
$error = $obj->validate();
if($error){
$error_msg = "".$error."";
$_SESSION['error_msgs'] = $error_msg;
header("location:".$_SERVER['HTTP_REFERER']."");
exit();
}else{
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit();
/*$fname = trim($_REQUEST["txt_fname"]);
$surname = trim($_REQUEST["txt_surname"]);
$phone = trim($_REQUEST["txt_contact"]);
$finamount = trim($_REQUEST['txt_finamount']);
$sel_loantype = trim($_REQUEST['sel_loantype']);
$message = '<html><body>';
$message .= '<table rules="all" width="100%" style="border:1px solid #666;" cellpadding="10">';
$message .= "<tr><td><strong>First Name:</strong> </td><td>" . strip_tags($fname) . "</td></tr>";
if($surname != ''){
$message .= "<tr><td><strong>Surname:</strong> </td><td>" . strip_tags($surname) . "</td></tr>";
}
$message .= "<tr><td><strong>Phone:</strong> </td><td>" . strip_tags($phone) . "</td></tr>";
$message .= "<tr><td><strong>Amount to Finance:</strong> </td><td>" . strip_tags($finamount) . "</td></tr>";
$message .= "<tr><td><strong>Loan Type:</strong> </td><td>" . strip_tags($sel_loantype) . "</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
$ToEmail = 'testemail#gmail.com';
$EmailSubject = "GET A QUICK QUOTE from ".strip_tags($fname);
$mailheader = "From: ".strip_tags($fname)."\r\n";
//$mailheader .= "Reply-To: ".$_REQUEST["txt_email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = $message;
if(#mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader)){
$_SESSION['sucess'] = "Your message has been sent successfully.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}else{
$_SESSION['sucess'] = "Sorry! Your message has not been sent.";
$_SESSION['form1data'] = $_REQUEST;
header("location: quick-quote.php");
exit;
}*/
}
}
?>
Step 2 Code:
<?php
error_reporting(0);
session_start();
require_once('validation.class.php');
?>
<script type="text/javascript">
function submitToCRM()
{
$.ajax({
type: 'POST',
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php',
data: $("#applynowform").serialize(),
beforeSend: function () {
$("#loadingimg").show();
},
success: function (){
//alert(data);
window.location.href = "http://www.test.com.au/thank-you";
}
});
Step 3: The above page sends data to quickquote-one.php form processing script which has below code.
<?php
if(!isset($_SESSION))
{
session_start();
}
$_SESSION['user_email'] = $_POST['email'];
Step 4: thank you page (this page has below code)
<?php
if(!isset($_SESSION))
{
session_start();
$_SESSION['user_email'] = $_POST['email'];
echo $_SESSION['user_email'];
}
?>
Add
session_set_cookie_params(0);
before your
session_start();
You can also pass the SID (session ID) between the pages using the URL to make sure it isn't lost in transition.
url: 'http://test.com.au/quick-quote/car-finance/quickquote-one.php?<?php echo htmlspecialchars(SID); ?>',
and
window.location.href = "http://www.test.com.au/thank-you?<?php echo htmlspecialchars(SID); ?>";
You're losing the session because you're sending the browser to the next URL without a relative path but instead a fully-qualified domain. This is a security measure to prevent session IDs from being inadvertently sent to the wrong server.
Another small solution would be to use relative paths like /page.php instead of http://www.domain.com/page.php
Read more here (PHP Manual)
In step 4 your setting
$_SESSION['user_email']
again. If the form has refreshed then your post is empty and you are overwriting the session with an empty value. Try removing it from step 4 and just leave.
<?php
if(isset($_SESSION['user_email']) && !empty($_SESSION['user_email']))
{
echo $_SESSION['user_email'];
}
?>
Also you are trying to echo your session email value IF the session is NOT set. I don't think that will work if the session is actually set..
i think it is better to start a session in one page and access all the session variables throghout if all the pages are connected to eachother. it will be some thing like we create login page. When user logs in capture alll the required values in a session and can be accessed through out the application even after refresh.
$query = "SELECT Useid,UserName,AccountStatus, FullName FROM Users WHERE UserName = :UserName";
from this query we can get the session variables easily.
if($login_ok)
{
//for last visit
$Month = 2592000 + time();
//this adds 30 days to the current time
setcookie(AboutVisit, date("F jS - g:i a"), $Month);
//last visit ends here.
$_SESSION['user'] = $row['UserName'];
$_SESSION['userid'] = $row['Useid'];
$_SESSION['fullname'] = $row['FullName'];
}
where ever you need th variable you can use like this
$username=$_SESION['user'];
I think this will work instead of startign session every time in each page.
Hope it helps
Beginner in php here.
I have the following form script:
<?php
if (isset($_POST['name']) && isset($_POST['email']) && isset($_FILES['uploaded_file']['name'])) {
$db_name = "xx";
$server = "localhost";
$DBuser = "xxx";
$DBpass = "xxxx";
$name = $_POST['name'];
$email = $_POST['email'];
$file = "Imagini_lume/" . $email . ".jpg";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Adresa de e-mail este incompleta!";
} else {
$name = trim($name);
if ($name != '') {
$temp_file = trim($_FILES['uploaded_file']['name']);
if ($temp_file != '') {
// here
mysql_connect($server, $DBuser, $DBpass) or die(mysql_error());
mysql_select_db($db_name) or die(mysql_error());
// check for existing
//$result = mysql_query("select email from Emails where email='$email'") or die(mysql_error());
$data = mysql_fetch_array($result);
if ($data == null) {
mysql_query("insert into Emails (Email,Full_Name,Image) values('$email','$name','$file');") or die(mysql_error());
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file)) {
//sucess
} else {
echo "Eroare incarcare imagine!";
}
// email sending
sendEmail("xx#gmail.com", getContent($name, $email, $file));
echo "Sucessfull!";
//} else {
//echo "Adresa de e-mail este folosita de cineva.";
}
} else {
echo "Trebuie sa selectati desenul dvs.!";
}
} else {
echo "Introduceti numele complet!";
}
}} else {
echo "Va rugam sa completati spatiile de mai sus!";
}
Note: if (isset($_POST['name']) && isset($_POST['email']) && isset($_FILES['uploaded_file']['name'])) { and } else {
echo "Va rugam sa completati spatiile de mai sus!";}
are on different lines than stated above. I only added that way so I can include all script inside the "code sample".
The questions are:
If the user uploads several files using the same name and e-mail address, the files will overwrite and I would like to differentiate the files (e.g. "name#email.com1.jpg","name#email.com2.jpg" and on).
I already found the script but being a beginner, I don't know where to insert the following code (another note- I don't know if it's the full code or some script is missing):
while(file_exists($name . $extension)) {
$name .= '1';
}
I would like to "oblige" the user to type it's full name. Due to design reasons I have only one "Full name" text box and I would like to force the user to type at least 2 words (first and last name) - basically a word minimum nr, not characters nr. Again, I have found a code, but still, I don't know how to apply it to my code, where to insert it:
if ($("#et_newpost_content").text().split(/\s+/).length < 250) {
alert('Message must be at least 250 words.')
}
Please advise.
Ok, it's quite simple. The first script to increment the image name counter is quite simple to implement:
1)
$db_name = "xx";
$server = "localhost";
$DBuser = "xxx";
$DBpass = "xxxx";
$name = $_POST['name'];
$email = $_POST['email'];
// Now checking the name existence
// Defining the initial state: the format is: my#email.com + counter + extension
// i.e. my#mail.com1.jpg
$ext = ".jpg";
$count = 1;
$base_file_name = "Imagini_lume/" . $mail;
// while already exists a file name like that, increment count
while (file_exists($base_file_name.$count.$ext))
$count++;
// finally define the official name of the file!
$file = $base_file_name.$count.$ext;
2) the code you wrote is javascript (jquery), not php... If you want to check the parameter server side you can use filter_var:
if (filter_var($name, FILTER_VALIDATE_REGEXP, array("options"=>array("regexp"=>"/^[A-Z][a-z]* [A-Z][a-z]*/"))) === FALSE)
die("Error: You should enter your complete name. i.e. John Black");
(take a look to regular expression chapter on the php guide)
Finally, please don't use that code in a real web application. As it's written, it's not safe on SQL injection attacks:
SQL Injection
Moreover you are not checking the correctness of each user input parameter. Take your time to make some experience ;)