There are many similiar questions but I don't have any error, where I need to do changes.
I have put alert boxes in my code but non are appearing.
Here is my code-
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql))
?>
<script> alert('Data Inserted successfully');
window.location.href='student.php?id=<?php echo $id;?>' </script>
<?php
}
}
You can wrap the script tag with all the js in string and echo it. it will work
if($conn->query($sql)){
echo "<script> alert('Data Inserted successfully')window.location.href='student.php?id="+$id+"</script>";
}
Try this:
if(isset($_POST['submit'])){
$test= "select * from stable where Email = '$Email'";
$queryResult = $conn->query($test);
$foundRows = $queryResult->num_rows;
if($foundRows >= 1)
$mailerr="Email already register";
else {
header("location:student.php?id=".$row['id']);
$sql = "INSERT INTO stable
(Firstname,Lastname,DOB,Email,Phno,
Gender,Address,City,ZipCode,State,Country,
Hobbies,Course,id,Time,Date,IP)
VALUES('$Firstname','$Lastname','$Dob','$Email',
'$Phno','$Gender','$Address','$City','$Zipcode',
'$State','$Country','$Hobby','$Course','',
'$Time','$date','$IP')";
if($conn->query($sql)){
echo "<script type='text/javascript'>alert('Data Inserted successfully');
window.location.href='student.php?id=".$id."';
</script>";
}
}
}
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>
Please see the scripts below. Onclick of Add gives an error when a php variable ($var)is used, however it will work with a number - i.e. if the line in index.php:
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>';
Is changed to something like:
echo '<button id="1" onclick="company_add(',57776,');">Add</button>';
What am I missing please?
Index.php:
<html>
<head>
<script type ="text/javascript">
function company_add(company_name) {
$.post('company_add.php', {company_name:company_name}, function(data) {
if (data == 'success'){
alert("Cool");
} else{
alert(data);
}
});
}
</script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<?php
include 'connect.php'; //Generic connect file
$var = 'Name';
echo '<button id="1" onclick="company_add(\''.$var.'\');">Add</button>
<br/>';
?>
</body>
</html>
company_add.php:
<?php
include 'connect.php';
function company_exists($company_name) {
return (mysql_result(mysql_query("SELECT COUNT(`company_name`) FROM
`company` WHERE `company_name` = $company_name"), 0) == 0 ) ? false :
true;
}
function add_company($company_name){
mysql_query("INSERT INTO `company` (`id`, `company_name`) values ('',
".$company_name.")");
}
$company_name = $_POST['company_name'];
if (company_exists($company_name) === true) {
echo 'Company already added';
} else {
add_company($company_name);
echo 'success';
}
?>
Use that line like this:
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
In case if you already have commas after and before the value of the $var you should trim it.
So use it like this:
$var = ltrim(",", $var);
$var = rtrim(", ", $var);
echo "<button id='1' onclick='company_add('" . $var . "');'>Add</button>";
And for your information yes you can even use a String instead of a Number too.
And UPDATE the functions:
function company_exists($company_name) {
$company_name = mysql_real_escape_string($company_name);
$query = "SELECT * FROM company WHERE company_name = '{$company}'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
return true;
}else{
return false;
}
}
function add_company($company_name){
$company_name = mysql_real_escape_string($company_name);
$query = "INSERT INTO company (id, company_name) VALUES ('', '{$company_name}')";
return mysql_query($query);
}
If you are using id field of that company table as AUTO_INCREMENT then you can leave the id field NAME & VALUE in the INSERT Statement.
Like This in the add_company Function:
$query = "INSERT INTO company (company_name) VALUES ('{$company_name}')"
I want to add comment on pressing enter and want to store it to my database with the specific t_id for it so that i can show it on the page after submission but when i enter text and press enter it does nothing.and i am also suspicious about my add_comment.php fule query because t_id is forgien key in comments table and primary in topics i am at very beginer level in jquery,php and ajax...Any Help will be appreciated.
Here is my Jquery From Send.php
$(document).ready(function(){
$('a').on('click',function(e){
$('#Comments').html('<textarea id="D_Comment" name="D_Comment"></textarea>');
$('a').on('input',function(ev){
$('#Enter_Comments').on('click',function(event){
var d_comnt = $('#D_Comment').val();
if (event.which == 13) {
alert("You Hit Enter");
e.preventDefault();
$.ajax({
url : "ajax/add_comment.php",
type : "POST",
data : {D_Comment : d_comnt},
success : function(data){
console.log(data);
},
error : function(data){
alert(data);
}
});
}
});
// ev.preventDefault();
// return false;
});
//e.preventDefault();
return false;
});
});
and my html from send.php on same page with php showing post from database
<section id="Main_Content">
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$last_id = mysql_real_escape_string($_GET['t_id']);
$sql = "SELECT * FROM Topics WHERE t_id = '".$last_id."'";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);
echo "<article>";
// echo $row['t_id'];
echo "<h2>".$row['name']."</h2>"."<br/>";
//echo "<a href='#'>".$row['date']."</a>";
// echo "<a href='#'>".$row['date']."</a>";
echo "<p> Posted on ".$row['date']."</p>"."<br/>" ;
echo "<p>".$row['detail']."</p>"."<br/>" ;
echo "<a href='t_id=".$row['t_id']."' id='Enter_Comments'>"."Enter Comment". "</a>";
echo "</article>";
?>
<div id="Comments"></div>
</section>
and my add_comment.php fiel is
<?php
mysql_connect("localhost","root","") or die("Could not coonnect");
mysql_select_db("forum") or die("could not select db");
$d_cmnt = mysql_real_escape_string($_POST['D_Comment']);
$t_id = mysql_real_escape_string($_GET['t_id']);
$sql = "INSERT INTO comments (comment,t_id,date) VALUES('$d_cmnt','$t_id',Now())";
$query = mysql_query($sql);
if ($query) {
echo "Success";
}
else{
echo "Error";
}
?>
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.
i am having some trouble with some script on my site.
i followed part of a tutorial as i liked the friend adding part but didn't want to change the whole site.
i used his code but obviously had to change some it to work on my site.
the idea is you visit someone else's profile and you can click to either block or send a friend request.
i am not sure where the issue is. i cant see any thing wrong in the php but is is possible i am missing something there as i am no expert, i am even less of an expert with javascript/ajax so this leads me to believe i have broken something in that.
here are my codes.
//Script on the profile.php page
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user <?php echo $username; ?>.");
if(conf != true){
return false;
}
_(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
_(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
_(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $id; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
_(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&id="+id);
}
//php script for the friend_system.php page
<?php
include_once("scripts/checkuserlog.php");
?>
<?php
if (isset($_POST['type']) && isset($_POST['id'])){
$id = preg_replace('#[^a-z0-9]#i', '', $_POST['id']);
$sql = "SELECT COUNT(id) FROM myMembers WHERE id='$id' AND activated='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$exist_count = mysqli_fetch_row($query);
if($exist_count[0] < 1){
mysqli_close($db_conx);
echo "$username does not exist.";
exit();
}
if($_POST['type'] == "friend"){
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$id' AND blockee='$logOptions_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM blockedusers WHERE blocker='$logOptions_id' AND blockee='$id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$blockcount2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count3 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='0' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count4 = mysqli_fetch_row($query);
if($blockcount1[0] > 0){
mysqli_close($db_conx);
echo "$user has you blocked, we cannot proceed.";
exit();
} else if($blockcount2[0] > 0){
mysqli_close($db_conx);
echo "You must first unblock $user in order to friend with them.";
exit();
} else if ($row_count1[0] > 0 || $row_count2[0] > 0) {
mysqli_close($db_conx);
echo "You are already friends with $user.";
exit();
} else if ($row_count3[0] > 0) {
mysqli_close($db_conx);
echo "You have a pending friend request already sent to $user.";
exit();
} else if ($row_count4[0] > 0) {
mysqli_close($db_conx);
echo "$user has requested to friend with you first. Check your friend requests.";
exit();
} else {
$sql = "INSERT INTO friends(user1, user2, datemade) VALUES('$logOptions_id','$id',now())";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "friend_request_sent";
exit();
}
} else if($_POST['type'] == "unfriend"){
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count1 = mysqli_fetch_row($query);
$sql = "SELECT COUNT(id) FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row_count2 = mysqli_fetch_row($query);
if ($row_count1[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$logOptions_id' AND user2='$id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else if ($row_count2[0] > 0) {
$sql = "DELETE FROM friends WHERE user1='$id' AND user2='$logOptions_id' AND accepted='1' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "unfriend_ok";
exit();
} else {
mysqli_close($db_conx);
echo "No friendship could be found between your account and $user, therefore we cannot unfriend you.";
exit();
}
}
}
?>
i have been looking at it now for a couple of days and am starting to not see the wood for the trees.
When i click on the request as fiend button, i get the dialog box fine, click ok and then it replaces the button with "please wait..." but that is where it stops. i have checked and nothing is being added to the database niether.
any help you could offer would be much apreciated.
thanks
I have provided an example of using jQuery to do this simply.
Here is what your button and response box would look like.
<div id="responsemessage<?php ///YOU USER ID FROM PHP// ?>" style="padding:2px; display:none;"></div>
<input name="" type="button" value="Friend Me" onClick="friendToggle('friend','<?php ///YOU USER ID FROM PHP// ?>')"/>
<input name="" type="button" value="Block Me" onClick="friendToggle('block','<?php ///YOU USER ID FROM PHP// ?>')"/>
This is what your jQuery function would look like. You will need to include the jQuery lib in your header.
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>function friendToggle(type,user){
///This is the ajax request via jQuery///
$.ajax({
url: 'friend_system.php?action='+type+'&user='+user,
success: function(data) {
///This is where the response from you php is handled. Sky's the limit//
if(data == 'good'){
$("#responsemessage"+user).html('You now have a friend.');
}else{
$("#responsemessage"+user).html(data);
}
}});
}</script>
</head>
And here is the php to process the requests this would be in your friend_system.php
<?php
include('YOUR CONNECTION DETAILS FILE');
$act = $_REQUEST['action'];
if($act == 'friend'){
$a = mysql_query("SELECT * FROM friends WHERE user1 = '".$_REQUEST['user']."'");
if(mysql_num_rows($a) > 0){
echo 'You are already friends.';
}else{
mysql_query("INSERT INTO friends SET user1 = '".$_REQUEST['user']."', user2 = '', datemade = '".date('d-m-Y H:i')."'");
echo 'good';
}
}
if($act == 'block'){
mysql_query("INSERT INTO blockedusers SET blocker='YOUR ID HERE, HOPE ITS PASSED VIA SESSION' AND blockee='".$_REQUEST['user']."'");
echo 'You have blocked this user.';
}
?>
I hope this helps you... Also be sure to check out http://jquery.com/