I'm making a basic login for a php website, the function is really simple if checks if the data send using POST is in a MySQL table and if it's correct it would allow the user to proceed it the data is incorrect, it should show a message saying credentials are incorrect:
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
}
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
?>
The if statement is working so far, and even the else but the message isn't showing out at all, I'm trying to look where exactly is the problem but I can't found it.
Try this code. Your brackets are in the wrong position.
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
}
?>
Like mentioned in the comments you have one curly braket that messes up your code. The else statement is now checking for the first if statement in which you check the request type. But the else case with the count should be the else case to your if statement that checks the number of rows ($count).
Furthermore you need to concatenate strings in your echo because your JS code doesnt know about variables or values from your PHP script like this:
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
Then try this
}else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
Try this one. Probably you have an extra bracket } or is wrongly positioned and you are echoing $message as a string which is wrong. Use concatenation in this way to print your message
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
header('Refresh: 0; URL=index.php');
Related
I new in programming. Currently, I develop a system that registration part. The registration part is successfully saved to the database. What I want to know is how to popup an alert dialog with one button e.g "Ok" after registration was successful and redirect to another page, such as home page. Now I only echo "successfully saved"
Below is my current code
<?php
require "DbConnect.php";
$name = $_POST['name'];
$badgeid = $_POST['badgeid'];
$position = $_POST['position'];
$department = $_POST['department'];
$factory = $_POST['factory'];
$reviewer = $_POST['reviewer'];
$title = $_POST['title'];
$year = $_POST['year'];
$month = $_POST['month'];
$suggestionwill = $_POST['suggestionwill'];
$present = $_POST['present'];
$details = $_POST['details'];
$benefit = $_POST['benefit'];
$sql_query = "INSERT INTO topsuggest (name,badgeid,position,department,factory,
reviewer,title,year,month,suggestionwill,present,details,benefit) VALUES('$name','$badgeid','$position','$department','$factory','$reviewer','$title','$year','$month','$suggestionwill','$present','$details','$benefit')";
if(mysqli_query($conn,$sql_query))
{
echo "<p id='msg'></p>";
}
else
{
echo "Error!! Not Saved".mysqli_error($con);
}
?>
Just use php header and use javascript to alert a message .
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: PATH TO BE REDIRECTED');
}
For a example
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: ../Insert/Index.php');
}
Please note that space between Location: is compulsory
After inserting data you can simply redirect to your interested page with a success message like:
header("location:page_of_interest.php?msg=Record Inserted");
and on page_of_interest.php you can simply check for msg and show if it is set like:
if(isset($_GET['msg'])){
echo $_GET['msg'];
}
when i execute my javascript this code why just else statement is working but not if,and when i use md5($_POST['password']) can't login?? but when not using md5 everything is ok
help me please :)
this is my database
this is my javascript
<script type="text/javascript">
$(document).ready(function() {
$("form#form_login").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url :'../assets/js/utama/login.data.php',
data:formData,
async:false,
cache:false,
contentType:false,
processData:false,
success:function(data){
if(data == "success")
{
window.location = '../index.php?hal=home';
}else{
alert('error');
}
}
});
});
return false;
});
</script>
this is my php file
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password'])
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
}else{
echo "alert('errorr')";
}
}
?>
You need to echo "success" in your PHP script response.
semicolon(;) missing md5($_POST['password']);
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
Please make sure all "password_user" column contain the md5 string in Database. So you have to store md5 for a password at the time of user registration. You have one non-md5 entry in the database for user "reza". So for this user md5($_POST['password']) will not match in database.
And write echo 'success'; in IF statement in PHP script.
In your code, in your select query there is space after $email and also you need to echo success when your if condition is executed. Improvise your php code as below:
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='".$email."' AND password_user='".$pass."'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "alert('errorr')";
}
}
?>
Hope this will help!
Yes It will always go in else part because you haven't eco success from php file then how can it will be go in success!!!??
change your php script to
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
}
?>
Also mark that don't use mysql* its deprecated and completely remove in PHP7. Use mysqli* or PDO instead
I've been trying to get a file-upload working for a website I'm working on. I'm doing this outside of a form, and after days of searching I finally found something that fits my method from the answer on this question:
The thing is, as soon as I applied the code to my own script, I got 'Undefined index' errors, and when I removed it, everything went fine.
Here is my code:
HTML
<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>
jQuery
function newsItem(action){
var thumbnail = $('#newsitem-thumbnail')[0].files[0];
var fileReader = new FileReader();
fileReader.readAsText(thumbnail, 'UTF-8');
fileReader.onload = shipOff;
function shipOff(e){
var r = e.target.result;
if(action == "insert"){
$.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
thumbnail:thumbnail.name,
action:action,
data:r},
function(result){
console.log(result);
console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
if(result == "succes"){
window.location.reload();
}else{
$(".error-msg").html(result);
}
});
}else if(action == "delete"){
//To be implemented when I get the submit working D:
}
}
}
PHP (Please excuse the mess -needs serious cleaning)
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
echo print_r($_POST);
echo var_dump($_POST);
$message = $_POST['message'];
$action = $_POST['action'];
$thumbnail = $_POST['thumbnail'];
$data = $_POST['data'];
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
if($_POST['message'] != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "succes";
}
}else if($action == "delete"){
$sql = "";
}
?>
Does anybody see what's going wrong here? Or does anyone have an alternative option?
I hope someone can help me out with this issue.
Change it like this:
include("../assets/libs/SQLLib.php");
DB_Connect("test");
print_r($_POST); //Dont echo, what is already echoed
var_dump($_POST); //Dont echo, what is already echoed
$message = !empty($_POST['message'])?$_POST['message']:'';
$action = !empty($_POST['action'])?$_POST['action']:'';
$thumbnail = !empty($_POST['thumbnail'])?$_POST['thumbnail']:'';
$data = !empty($_POST['data'])?$_POST['data']:'';
if(!empty($thumbnail) && !empty($data)){
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
} else {
echo json_encode(array('error'=>'No data and thumbnail assigned'));
}
if($message != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "success";
}
}else if($action == "delete"){
$sql = "";
}
As well you only need to change error reporting level in .htaccess or php in order to prevent warning message to be displayed. In .htaccess:
php_flag error_reporting E_ERROR
If in .php file then
<?php error_reporting(E_RROR); //This displays only Errors, no warning and notices.
Hope you have tried using
isset($_POST) or isset($_POST['message']) if you get "Notice: Undefined index: message".
So in the end I opted out of a full jQuery-upload, and went for something else.
I am now uploading files purely through a PHP call, instead of a jQuery post event, with a small JavaScript check next to it to see if the form is submittable.
The code:
HTML
<div class='error-msg'></div>
<form method='post' action='requestPages/newsitems.php' enctype='multipart/form-data'>
News message
<textarea id='newsitem-message' name='newsitem-message' onchange='checkFormSubmit()'/>
<input type='file' name='newsitem-thumbnail' id='newsitem-thumbnail' />
<input hidden type='text' value='insert' name='newsitem-action'/>
<input class='submit' id='newsitem-submit' type='submit' value='Post news' disabled/>
</form>
PHP
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
var_dump($_FILES);
var_dump($_POST);
$message = $_POST['newsitem-message'];
$action = $_POST['newsitem-action'];
$errors= array();
$hasFile = false;
if($action == "insert"){
echo ($_FILES['newsitem-thumbnail'][0] == UPLOAD_ERR_NO_FILE);
if(isset($_FILES['newsitem-thumbnail']) && $_FILES['newsitem-thumbnail']['error'] != UPLOAD_ERR_NO_FILE){
$file_name = $_FILES['newsitem-thumbnail']['name'];
$file_size =$_FILES['newsitem-thumbnail']['size'];
$file_tmp =$_FILES['newsitem-thumbnail']['tmp_name'];
$file_type=$_FILES['newsitem-thumbnail']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['newsitem-thumbnail']['name'])));
$extensions= array("jpeg","jpg","png");
if(!in_array($file_ext,$extensions)){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
$hasFile = true;
}
if(empty($errors)){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$file_name."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
if($hasFile){
if(!move_uploaded_file($file_tmp,"../assets/images/thumbnails/".$file_name)){
echo "Moving the file failed!";
}
}
}
}else{
print_r($errors);
}
}else if($action == "delete"){
$sql = "";
}
?>
JavaScript
function checkFormSubmit(){
if($.trim($('#newsitem-message').val()) != ""){
$('#newsitem-submit').prop('disabled', false);
}else{
$('#newsitem-submit').prop('disabled', true);
}
}
I am creating a messaging system for a website that I am making. Basically, it consists of clicking one button and two Ajax Requests afterwards. I am not even sure I am going about this the right way. On click of the button the first Ajax starts to call. The first ajax request loads a file that loads the style of the messages and retrieves them from a database. The problem I am having is that the first request sometimes takes to long to finish and the other request does not get complete. Another problem I am having is that if I put an "animation delay" type thing on it then it will look like the page it running slow. You can run an example at "http://www.linkmesocial.com/linkme.php?activeTab=mes" you must type or copy and past the whole length for it to work otherwise you will redirect to the login page. Any advice would be AWESOME! If there is some easier way to set up a messaging system please feel free to give me some advice or direct me to a tutorial. THANK YOU SO MUCH!
I would also like the know if this is a good practice. Please :)
My Original file. On click of class "mes_tab" a form is submitted. also the function mes_main() is called.
session_start();
$username = $_SESSION['user'];
$messages = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username'");
echo "<div id=\"mes_main-bar_top\" class=\"center\">Messages</div>";
echo "<div id=\"mes_main\">";
echo "<table id=\"mes_main-allView\" class=\"left\">";
echo "<td class=\"mes_tab-change\" >^</td>";
$from=array("","","", "", "", "", "", "");
for ($msgCount = 0; $msgCount < 8; $msgCount++){
$row = mysqli_fetch_array($messages);
$from[$msgCount] = $row['sender'];
for ($prev = 0; $prev < $msgCount; $prev++)
{
if ($from[$msgCount] == $from[$prev] )
{
$cont = true;
break;
}
}
if ($cont)
{
$cont = false;
continue;
}
if ($row['message'] == ""){
break;
}
echo "<tr><td class=\"mes_tab\" onclick=\"mes_main('" . $row['sender'] . "')\">";
echo "<h3 class=\"center\">" . $row['sender'] . "</h3>";
echo "<form id=\"" . $row['sender'] . "\" >";
echo "<input name=\"sender\" value=\"" . $row['sender'] . "\" hidden/>";
echo "<input name=\"id\" value=\"" . $row['id'] . "\" hidden/>";
echo "</form>";
echo "</td></tr>";
}
if ($msgCount == 8)
{
echo "<td id=\"mes_tab-change_bottom\" class=\"mes_tab-change\">V</td>";
}
echo "</table> <!-- end mes_main-allView -->";
echo "<div id=\"mes_main-mesView\" class=\"right\">";
echo "</div> <!-- end mes_main-mesView -->";
echo "</div> <!-- end mes_main -->";
mes_main() function from above. The two ajax functions inside are what I am referring to in the post above.
function mes_main(x)
{
var sender = x;
$( sender ).submit(function( event ) {
event.preventDefault();
});
ajax_req_mes("scripts/home/php/mes_load.php?" + sender , "mes_main-mesView");
ajax_req_mes("scripts/home/php/mes_content.php?" + sender ,"mes_content");
}
mes_load.php
the $sender var is created by passing the sender username through the URL. That is why I do php explode on the url.
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<div id=\"mes_content\"></div>";
echo "<div id=\"mes_field\" class=\"right\"></div>";
mes_content.php
session_start();
$username = $_SESSION['user'];
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$sender = explode('?', $url);
$recieved = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$username' AND sender='$sender[1]'");
$sent = mysqli_query($con, "SELECT * FROM messages WHERE recipient='$sender[1]' AND sender='$username'");
echo "<table id=\"mesView-table\">";
$REC = array();
$SENT = array();
$ID = array();
for ($i = 0; $i < 25; $i++)
{
$rec = mysqli_fetch_array($recieved);
$sent = mysqli_fetch_array($sent);
if ($rec['id'] > 0)
{
$REC[$i] = $rec['id'];
}
if ($sent['id'] > 0)
{
$SENT[$i] = $sent['id'];
}
}
$ID = array_merge($SENT, $REC);
sort($ID);
for ($x = 0; $x < count($ID); $x++)
{
$key = $ID[$x];
$result = mysqli_query($con, "SELECT * FROM messages WHERE id = '$key'");
$res = mysqli_fetch_array($result);
if (in_array($key, $REC))
{
echo "<tr><td class='mes_recieved'>";
echo $res['message'];
echo "</tr></td>";
}
elseif (in_array($key, $SENT))
{
echo "<tr><td class='mes_sent'>";
echo $res['message'];
echo "</tr></td>";
}
}
echo "</table>";
Set async to false in your ajax requests!That's how the second one will wait for completing the first one and then start.
Also you can catch the on success and on error for the purposes you have.
Just use the "success" and "error" callbacks.
Also you could use the "done" callback
But, IMO, for that kind of problem I think a better alternative would be using Websockets
EDIT:
Here is some example of how you could do it:
jQuery.ajax({
type : "POST",
data : {msg:"your message"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
}).done(secondCall());
function secondCall(){
jQuery.ajax({
type : "POST",
data : {data:"data"}
url : "http://fu.com/myfile.php",
success: function(response){
//Do something with your response
}
});
}
EDIT2:
For visibility, here is a tutorial using websockets: http://www.sanwebe.com/2013/05/chat-using-websocket-php-socket
I am using AJAX in order to access data from a php file.
I have problem with the format of retrieved data from database, please help.
So, this is my ajax function splice. It retrieves data from find_account.php
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
form_prof.prof_id.value = req.responseText;
form_prof.prof_name.value = req.responseText;
form_prof.prof_username.value = req.responseText;
form_prof.prof_password.value = req.responseText;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
find_account.php
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
echo 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$id = $arr['profs_number'];
$name = $arr['profs_name'];
$username = $arr['profs_username'];
$password = $arr['profs_password'];
}
header("Content-type: text/plain");
echo $id;
echo $name;
echo $username;
echo $password;
?>
and I have 4 input boxes in my HTML from where the req.responseText puts the value
and everytime I search the name in the input field for example:
Search: [ Dorothy Perkins ]
The output goes like [id,name,username,password]:
[20111Dorothy Perkinsdperkins#mail.com123456] [same with 1st field] [same] [same]
Wherein I want it to be like...
[20111] [Dorothy Pekins] [dperkins#mail.com] [123456]
Where [ ] are input fields.
Please help me arrange my format, I am so confused. I am new to this.
You can encode return values in json before sending back.
In PHP
<?php
include("connect.php");
session_start();
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if(empty($num))
{
$returnValues = 'DATA NOT FOUND';
}
else
{
$arr = mysql_fetch_array($result);
$returnValues = json_encode($arr);
}
echo $returnValues;
?>
In Javascript
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
req = JSON.parse(reg);
form_prof.prof_id.value = req.id;
form_prof.prof_name.value = req.name;
form_prof.prof_username.value = req.username;
form_prof.prof_password.value = req.password;
}
else {
alert("Problem in retrieving the XML data:\n" + req.statusText);
}
}
}
You have to write the data in some format from your PHP code (XML, json, or simply separate the values with a comma), and parse it from your javascript.
For example, in PHP:
echo $id . "," . $name . "," . $username . "," . $password;
And then in the javascript:
values = req.responseText.split(",");
form_prof.prof_id.value = values[0]
form_prof.prof_name.value = values[1];
form_prof.prof_username.value = values[2];
form_prof.prof_password.value = values[3];
Of course you may have to do something more complicated if the values may contain a comma.
You can try this
$account = $_GET['account'];
$query = "SELECT * FROM profs WHERE profs_name = '".$account."'";
$result = mysql_query($query, MYSQLI_STORE_RESULT);
while($arr = $result->fetch_array(MYSQLI_ASSOC)) {
$returnValues = json_encode($arr);
break;
}
echo $returnValues;
Note that column names are used as associative index for $arr
Hope it works.