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>";
}
}
Related
I'm trying to use php to run a sql select statement to pull data from a database and then only output one column(username) to an array that I can then use to filter using a JS script. Similar to how facebook/twitter does their real time searching of contacts when you start typing someone's name in. I keep getting an error though in php when I try to pull the username column and set it to an array and output that:
<?php
session_start();
include_once 'dbconnect.php';
$contact = mysql_real_escape_string($con, $_POST['contact']);
$sql = "select * from users";
$result = $con->query($sql);
if ($result->num_rows > 0) {
($row = $result->fetch_assoc()) {
printf($row["username"]);
}
} else {
echo "0 results";
}
?>
It would help to know what the exact error PHP is giving you is. But from a cursory look on your code I believe you are missing a while keyword.
while ($row = $result->fetch_assoc()) {
printf($row["username"]);
}
I am trying to pass user's info from mysql to the webpage, if the user has logged in but can't get it to work. If I put a wrong email or password it will show the error message but if the credentials are ok it would do anything...
on php file:
$sql = "SELECT * FROM users WHERE email='$l_email' AND password='$l_password'";
$query = mysql_query($sql) or die ('Error: ' . mysql_error());
$num_rows = mysql_num_rows($query);
if($num_rows < 1)
{
echo "You have entered a wrong email or password!";
}
else {
$memberInfo = array();
while( $row = mysql_fetch_array( $query ) )
{
$memberInfo[] = $row;
}
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
}
on js file:
$.post("./includes/checkOut.php",{ l_email1: l_email, l_password1: l_password },
function(data) {
if(data=='1')
$("#checkOut_form")[0].reset();
$("#login_returnmessage").html("");
$("#memberInfo").hide("");
var memberInfo = jQuery.parseJSON(memberInfo);
for( var i in memberInfo )
{
var f_name = memberInfo[i].f_name;
var l_name = memberInfo[i].l_name;
var phone = memberInfo[i].phone;
}
$("#loggedinInfo").show("");
$('#_f_name').val(f_name);
$('#_l_name').val(l_name);
$('#_email').val(l_email);
$('#_phone').val(phone);
}
$("#login_returnmessage").html(data);
});
If you use return outside a function then it terminates the script at that point. This is exactly what you're doing here:
return $memberInfo;
echo json_encode( $memberInfo );
//echo "1";
You need to remove the return statement.
You should also add a Content-type: header to the response to tell the browser to expect JSON:
header('Content-type:application/json');
echo json_encode( $memberInfo );
Your Javascript code is checking the response for the value 1, which you're not sending, so the code that updates the display won't execute.
Lastly:
don't store passwords unencrypted - use password_hash()
don't use mysql as it's deprecated - use mysqli or PDO
ensure you escape your inputs before passing them to the database (or better, use prepared statements (not supported by mysql_*()).
I have this JavaScript code that is working well:
var lookup = {
"dog-black":{url:'images/dog-black.jpg'},
"dog-white":{url:'images/dog-white.jpg'},
"cat-black":{url:'images/cat-black.jpg'},
"cat-white":{url:'images/cat-white.jpg'}
};
I'm tring to generate same code dynamically using PHP to have lines as much as there in the DB, like this:
var lookup = {
<?php
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '"'.$row['name'].'":{url:images/'.$row['name'].'.jpg';
}
} else {echo "No records";}
?>
};
I tried to define the php code as string using quotes or heredoc and alert the string variable, but seems like the script is not excuted
note: i'm already connected to the DB before this part of code and pass data from/to it.
Don't try to echo this out manually. What you can do is build the same structure in PHP, then use json_encode.
JSON is actually valid JavaScript code, so it will work.
Try it like this:
<?php
$lookup = array();
$sql = "SELECT name FROM swords ORDER BY animals, colors";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$lookup[$row['name']] = array('url' => 'images/'.$row['name'].'.jpg');
}
}
else {
//echo "No records";
}
?>
var lookup = <?=json_encode($lookup); ?>;
There seems to be a mistake in the echo in the while loop. You're not closing the string correctly, it is missing the closing part },. Which should look something like this:
echo '"'.$row['name'].'":{url:"images/'.$row['name'].'.jpg"},';
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 !