I tried to write a script mixing something I found on the internet in order to autosave a form data to the mysql db... Something went wrong cause the script it is able to insert but for some reason not to update so every 20 sec (the time I set up) is generating a new row... Can anyone help me to find and solve the issue?
Here is the code:
<?php
session_start();
unset($_SESSION['article_id']);
require_once('xajax/xajax_core/xajax.inc.php');
$xajax = new xajax();
function savetodb($form) {
$title = $form["title"];
$editor = $form["editor1"];
//$host = 'localhost';
//$username = 'my_user';
//$password = 'my_pass';
//$database = 'test_db';
//$connect = mysql_connect($host, $username, $password);
//mysql_select_db($database, $connect);
if ($_SESSION['article_id']=="") {
$sql = "INSERT INTO draft (`title`, `content`) VALUES ('$title', '$editor')";
$result = mysql_query($sql, $connect);
$idlast = mysql_insert_id($connect);
$_SESSION['article_id'] = $idlast;
} else {
$article_id = $_SESSION['article_id'];
$sql = "UPDATE draft SET `title`='$title',`content`='$editor' WHERE `id`='$article_id'";
$result = mysql_query($sql, $connect);
}
// Instantiate the object xajaxResponse
$objResponse = new xajaxResponse();
$objResponse->assign("autosavemsg","innerHTML", "<br />Record saved to database successfully!");
$objResponse->alert('Done!');
return $objResponse;
}
//$xajax->register(XAJAX_FUNCTION,'savetodb');
$xajax->registerFunction('savetodb');
$xajax->processRequest();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<?php $xajax->printJavascript('xajax'); ?>
</head>
<body>
<form name="form" id="form" enctype="multipart/form-data">
<?php
echo '<label>Title</label><input type="text" name="title" id="title"><br /><br />';
echo '<textarea name="editor1"></textarea>' ;
?>
<input type="button" name="save" onclick="xajax_savetodb(xajax.getFormValues('form'));" value="Save to Database">
</form>
<div id="autosavemsg"></div>
<script language="Javascript">
//Interval
var AutoSaveTime=20000;
//time object
var AutoSaveTimer;
SetAutoSave();
function SetAutoSave() {
AutoSaveTimer=setInterval("xajax_savetodb(xajax.getFormValues('form'));",AutoSaveTime);
}
</script>
</body>
</html>
Unfortunately is not even give to me the alert "done" or the message that I set..
Probably something wrong with the session??
thanks in advance
I'm not familiar with xajax but referring to my logic, I think you are doing it wrong.
I think you have to have two different files, one is your HTML and javascript and other one is your server-side code which is responsible for inserting or updating the db.
right now as I think you are calling the file itself with ajax and in the third line of the code you have unset($_SESSION['article_id']); which will unset the session variable $_SESSION['article_id'] each time you call the ajax.
so I think you have to make two different files.
file1.php
you have your html and javascript files in it and also have the unset($_SESSION['article_id']); line in it.
files2.php you have your php and db related functions in it and delete the unset($_SESSION['article_id']); line from it.
you also have to set in file1.php that your ajax should call file2.php
I think this will do the trick
Related
I've been trying to create an admin panel for my website. I created a login form but whenever I try to log in, it says that the user does not exist. I can't seem to find where I made a mistake.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
include 'db.php';
?>
<?php
include 'functions.php';
?>
<?php
include 'title_bar.php';
?>
<h3>Login Here: </h3>
<?php
if(isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) or empty($password)){
echo "<p>Fields should not be empty</p>";
} else {
$check_login=mysqli_query($con,"SELECT id, type FROM users WHERE username='$username' AND password='$password'");
if(mysqli_num_rows($check_login) == 1){
$run=mysqli_fetch_array($check_login);
$user_id=$run['id'];
$type=$run['type'];
if($type =='d') {
echo "<p>Your acount is deactivated by an admin!</p>";
} else {
$_SESSION['user_id'] = $user_id;
header('location: adminpanel.php');
}
} else {
echo "<p>Wrong Username or Password</p>";
}
}
}
?>
<form method='post'>
User name:
<input type ='text' name = 'username' />
<br/><br/>
Password:
<input type = 'password' name = 'password' />
<br/><br/>
<input type = 'submit' name = 'submit' value='Login' />
</form>
</body>
</html>
Any help would be appreciated.
Just because I see this all the time on SO, I will address some of my comments. There are a lot of reasons why it could fail based on what you have. First off, a solid framework would do almost all this for you, you would just have to do basic logic but not all the grunt work. Second, just because you want to echo some text in a specific part of your page, doesn't mean you should do a bunch of logic that leads up to echo in the same part of the page. The idea is that the browser output is the last thing to happen so you will want to do the bulk of your logic before the page outputs.
First break up your logic into a specific-task functions/class/methods that will be easily understood and ready to be re-used:
/functions.php
<?php
// I am going to use PDO because I am more familiar with it
function verifyUser($username,$password,$con)
{
// Get the basics from the database
$query = $con->prepare("SELECT `password`,`type`,`id` FROM `users` WHERE `username` = :0");
// Bind the value for security
$query->execute(array(":0"=>$username));
// Get the results
$result = $query->fetch(PDO::FETCH_ASSOC);
// If empty, return false
if(!$result)
return array('verified'=>false);
// You need to store the password using password_hash()
$verified = password_verify($password,$result['password']);
// If user is revoked
$revoked = is_deactivated($result);
// Return all the validation settings
return array(
'type'=>$result['type'],
'id'=>$result['id'],
'revoked'=> $revoked,
'verified'=>$verified,
'valid'=>($verified && !$revoked)
);
}
function getUserById($id,$con)
{
$query = $con->prepare("SELECT * FROM `users` WHERE `id` = :0");
$query->execute(array(":0"=>$id));
$result = $query->fetch(PDO::FETCH_ASSOC);
if(!$result)
return false;
return $result;
}
function is_deactivated($userArr = false,$con = false)
{
// Set default user empty
$user = false;
// If value is numeric (id)
if(is_numeric($userArr)) {
// Get the data by from database, assign to user
$user = getUserById($userArr,$con);
}
// If the value is an array, just assign to user
elseif(is_array($userArr))
$user = userArr;
// If the value is still empty, stop, return deactivated
if(empty($user))
return true;
else
// If user is valid (in db), return bool if they are revoked
return ($user['type'] == 'd');
}
function loginObserver(&$error,$con)
{
// See if the action to log in is set
if(isset($_POST['action']) && $_POST['action'] == 'login') {
// Run the verify function
$verify = verifyUser($_POST['username'],$_POST['password'],$con);
// If user is in db
if($verify['verified']) {
// See if they are revoked, send back error
if($verify['revoked']) {
$error = 'revoked';
return false;
}
// Assign your session id
$_SESSION['user_id'] = $verify['id'];
// Return true for success
return true;
}
else {
// User was not in system, send invalid error
$error = 'invalid';
return false;
}
}
else
// Return a string so the subsequent logic knows that
// no attempt was made to log in.
return 'invalid';
}
Secondly, now that you have all your business logic stored away in contained functions (classes/methods) you can cleanly apply them to the page.
/login.php
<?php
// Put this at the very beginning. I would consider putting it on a config page and
// including it would be better because then you will have some consistency
// through your site
session_start();
// Add your functions and or classes, better yet would be to have an autoloader
// to load classes and a pseudo-autoloader to load functions
include('functions.php');
// Put your database connection at the top, on the config page would be better
include('db.php');
// Move logic to the top and pass errors to the page
$error = false;
// Run the observer function
$login = loginObserver($error,$con);
// Invalid means no attempt was made to login
if($login != 'invalid')
// If there are no errors (empty), redirect
if(!$error) {
// This needs to go before output of html to browser
header('location: adminpanel.php');
// Stops the script from processing the rest of the page
exit;
}
}
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login - Admin panel</title>
</head>
<body>
<?php
// This is probably fine, it's likely just html
include('title_bar.php');
?>
<h3>Login Here: </h3>
<?php if($error) {
echo ($error == 'invalid')? 'Wrong username or password.':'Your access has been revoked by admin.';
} ?>
<form method='post'>
<!-- add an action here -->
<!-- You should do a token system for verifying submission authenticity -->
<input type="hidden" name="action" value="login" />
User name:
<input type='text' name='username' />
<br/><br/>
Password:
<input type='password' name='password' />
<br/><br/>
<input type='submit' name='submit' value='Login' />
</form>
</body>
</html>
Finally, this code is not tested so there may be errors in logic. It is intended to show you how to apply my (and perhaps other's comments practically). I don't want to say "Don't do this and don't do that" but don't show an alternative. This script is based on yours so you can identify similarities easier, but is no way implied this is the only way, or the correct way to do a login.
So I looked into other threads but didnt find a solution that worked for me.
Here is my problem:
I have two php pages:
http://codepad.org/VhblM76K and
http://codepad.org/W9bz8L3E.
The first page is supposed to get information from a form, look for it in a database, store it in a variable $_SESSION['$dataArray'] and send it to the second page.
On the second page I get the information in javascript from php with json_encode, which gives an error:
Uncaught SyntaxError: Unexpected token < result.php:20.
When I look in the source in chrome it says:
var schoolData = <br />
<b>Notice</b>: Undefined index: $dataArray in <b>C:\xampp\htdocs\highschools.bg\result.php</b> on line <b>23</b><br />
null;
How is this an unidentified index, when i can only go to the second page after visiting the first one, where I assing a value to $_SESSION['$dataArray'].
How can I fix this? I have written session_start() in both pages and it didnt work for me.
I need the variable schoolData to show the information on the page.
The reason why you're getting the error is because you're not setting any session data, because you are redirecting directly to the second page from the form.
You need to update the form so it redirects back to the same page the form is on, then replace your PHP code with the following:
if (isset($_POST['submit'])) {
$user = 'root';
$pass = '';
$db = 'highschools';
$con = mysqli_connect('localhost', $user, $pass, $db) or die("Unable to connect");
if (mysqli_connect_errno()) {
echo("Failed to connect to MySQL: " . mysqli_connect_error());
}
$givenCity = $_POST['city'];
$givenClass = $_POST['class'];
$givenName = $_POST['name'];
$result = mysqli_query($con,
"SELECT * FROM highschools WHERE name like '%$givenName%' AND city like '%$givenCity%' AND class like '%$givenClass%'; ") or die(mysqli_error($con));
$row_count = mysqli_num_rows($result);
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}
header('location: http://YOUR_SECOND_PAGE_ADDRESS');
Notice, the only line I've added is the last line, hedaer('location: ... ');
Don't forget to change the http://YOUR_SECOND_PAGE_ADDRESS to the actual page address of your second piece of code.
Then in the second page, replace $_SESSION['$dataArray'] with $_SESSION['dataArray']
and it should work.
Your problem is that you are writing the session as $_SESSION['$dataArray']. If you have a variable somewhere called $dataArray then you need to write it $_SESSION[$dataArray].
Alternately, if you don't have a variable named $dataArray, then you need to write it as $_SESSION['dataArray'].
EDIT:
Try print_r($_SESSION) beneath the session_start() at the top of the page and see if you have set that the $_SESSION['dataArray']:
<?php
session_start();
// See if the session contains your $_SESSION['dataArray']
// If not, you can force it to have a default value to avoid errors
print_r($_SESSION);
$_SESSION['dataArray'] = (isset($_SESSION['dataArray']))? $_SESSION['dataArray']:array(); ?>
<!DOCTYPE html>
<html>
<head>
<title>Намерени училища</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/main.css">
</head>
<body>
<div id="contentWrapper" style="height:1000px;">
<header id="pageHeader">
</header>
<section id="schoolsContainer">
<ul id="schoolsList"></ul>
</section>
</div>
<script type="text/javascript" src="handlebars-v2.0.0.js"></script>
<script type="text/javascript" src="navTemplate.js"></script>
<script type="text/javascript">
var schoolData = <?php echo json_encode($_SESSION['dataArray']) ?>;
for (var i = 0; i < schoolData.length; i++) {
console.log(schoolData[i]['name']);
console.log(schoolData[i]['id']);
}
</script>
</body>
</html>
On the other page, this also has to be set before it works:
$_SESSION['dataArray'] = array();
while($row_count > 0) {
$curRow = mysqli_fetch_array($result);
$_SESSION['dataArray'][] = $curRow;
$row_count--;
}
I am trying to learn some new stuff and always wanted to learn how to make a website with PHP and mysql...
I found this easy tutorial and sample files to play with
http://css-tricks.com/php-for-beginners-building-your-first-simple-cms/
I'm trying to add another table it works in the database but when I try to display it it don't work. Here is the code I got and using:
<?php
class simpleCMS {
var $host;
var $username;
var $password;
var $table;
public function display_public() {
$q = "SELECT * FROM laptopvoltage ORDER BY created DESC LIMIT 3";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$lvmodel = stripslashes($a['lvmodel']);
$lvmanuf = stripslashes($a['lvmanuf']);
$lvvolt = stripslashes($a['lvvolt']);
$entry_display .= <<<ENTRY_DISPLAY
<div class="post">
<h2>
$lvmodel
</h2>
<p> !!!!!!this dont show upp!!!!!! - - - - >>>>>
$lvmanuf
</p><----------- WHY?
<p>
$lvvolt
</p>
</div>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<h2> This Page Is Under Construction </h2>
<p>
No entries have been made on this page.
Please check back soon, or click the
link below to add an entry!
</p>
ENTRY_DISPLAY;
}
$entry_display .= <<<ADMIN_OPTION
<p class="admin_link">
Add a New Entry
</p>
ADMIN_OPTION;
return $entry_display;
}
public function display_admin() {
return <<<ADMIN_FORM
<form action="{$_SERVER['PHP_SELF']}" method="post">
<label for="lvmodel">Title:lv model</label><br />
<input name="lvmodel" id="lvmodel" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvmanuf">Title:lv manu</label><br />
<input name="lvmanuf" id="lvmanuf" type="text" maxlength="150" />
<div class="clear"></div>
<label for="lvvolt">Title:lvvolt</label><br />
<input name="lvvolt" id="lvvolt" type="text" maxlength="150" />
<div class="clear"></div>
<input type="submit" value="Create This Entry!" />
</form>
<br />
Back to Home
ADMIN_FORM;
}
public function write($p) {
if ( $_POST['lvmodel'] )
$lvmodel = mysql_real_escape_string($_POST['lvmodel']);
if ( $_POST['lvmanuf'] )
$lvmanuf = mysql_real_escape_string($_POST['lvvolt']);
if ( $_POST['lvvolt'] )
$lvvolt = mysql_real_escape_string($_POST['lvvolt']);
if ( $lvmodel && $lvmanuf && $lvvolt ) {
$created = time();
$sql = "INSERT INTO laptopvoltage VALUES('$lvmodel','$lvmanuf','$lvvolt','$created')";
return mysql_query($sql);
} else {
return false;
}
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this->buildDB();
}
private function buildDB() {
$sql = <<<MySQL_QUERY
CREATE TABLE IF NOT EXISTS laptopvoltage (
lvmodel VARCHAR(150),
lvmanuf TEXT,
lvvolt VARCHAR(150),
created VARCHAR(100)
)
MySQL_QUERY;
return mysql_query($sql);
}
}
?>
it just wont show $lvmanuf. Any help on this would be great as the fields are showing up in my database.
this first file only shows results, if your not to familiar with web logic and design then ill try my best to explain, this first file is called index.php, every website and web-application has a file either call index.html or index.php the reason behind this is that the web server looks for a file named either index.html or index.php and dont misunderstand there are more than just these file types and names a server can start off of its just that these are the most common, since that is out of the way now i will explain the code behind the first file.
as you can see we have set up our basic html document inside and added a script, now the script we made will make the files that are loaded inside the id we specified disappear after a set ammount of seconds, next inside the body of the html we put this code,
<span id="messages">
<?php include "constant.php"; ?>
</span>
this code contains to main players for this script first the span tag with the id attribute tells our javascript the id of the text we want to be invisible after the set amount of seconds, next the
<php include "constant.hpp"; ?>
it includes every thing from the constant.php document we make.
file 1
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" /><meta http-equiv="content-language" content="en-US" />
<title>MySQL Connection test</title>
<script type="text/javascript">
window.onload = function()
{
timedHide(document.getElementById('messages'), 10);
}
function timedHide(element, seconds)
{
if (element) {
setTimeout(function() {
element.style.display = 'none';
}, seconds*1000);
}
}
</script>
</head>
<body>
<span id="messages">
<?php include "constant.php"; ?>
</span>
</body>
</html>
this second file im not going to explain to much about it, since it would make this way to long, but this file is the connection file to the mysql database.
the only part you need to fill in on this is the
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
this will connect your website to the database.
file 2
constant.php
<?php
$database_ip = ""; //database ip adress goes inside quotes
$database_port = ""; //database port goes inside quotes
$database_name = ""; //database name goes inside quotes
$database_admin_user = ""; //admin username goes inside quotes
$database_admin_pass = ""; //admin password goes inside quotes
//do not modify anything past this point unless you know php well.
$database_link = null;
$database_defaults = array("127.0.0.1","3306","MySQL","root","");
$error_defaults = array("error_no_101" => "required field *IP is empty, using default parameters!",
"error_no_102" => "required field *PORT is empty, using default parameters!",
"error_no_103" => "required field *NAME is empty, using default parameters!",
"error_no_104" => "required field *USER is empty, using default parameters!",
"error_no_105" => "required field *PASS is empty, using default parameters!");
if(empty($database_ip)){
$database_ip = $database_defaults[0];
echo $error_defaults["error_no_101"] . "<br/>";
}
if(empty($database_port)){
$database_port = $database_defaults[1];
echo $error_defaults["error_no_102"] . "<br/>";
}
if(empty($database_name)){
$database_name = $database_defaults[2];
echo $error_defaults["error_no_103"] . "<br/>";
}
if(empty($database_admin_user)){
$database_admin_user = $database_defaults[3];
echo $error_defaults["error_no_104"] . "<br/>";
}
if(empty($database_admin_pass)){
$database_admin_pass = $database_defaults[4];
echo $error_defaults["error_no_105"] . "<br/>";
}
$database_link = mysqli_connect($database_ip, $database_admin_user, $database_admin_pass, $database_name);
if (!$database_link) {
die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error());
} else {
echo 'Success... ' . mysqli_get_host_info($database_link) . "\n";
}
mysqli_close($database_link);
?>
i put this up to help you fix your code, not to teach you the syntax of the language.
to learn the syntax of php i recommend you go here:
this is the official php website documentation that teach you the correct way to code php,
http://www.php.net/manual/en/langref.php
you could also try this place if you have the money for a subscription:
http://www.lynda.com/MySQL-tutorials/PHP-MySQL-Essential-Training/119003-2.html?srchtrk=index:1%0Alinktypeid:2%0Aq:php%0Apage:1%0As:relevance%0Asa:true%0Aproducttypeid:2
for html you could go to:
http://www.w3schools.com/html/default.asp
you could also try this place if you have the money for a subscription:
http://www.lynda.com/HTML-tutorials/HTML-Essential-Training-2012/99326-2.html
I have a form that ask the email of the new user. I got a php function that can use this email to get informations (firstname, lastname, office, job...) using a cURL request and return it into an array ($full_informations).
I want this function to be executed after an email has been entered. For different reasons, I cannot directly add code to my form, so I need something can be read somewhere else in the body or the head.
I got this field that is automatically populated by a script:
<input onKeyPress="" class="editingSize " type="text" id="emails" name="emails" size="" value="" maxlength="150">
I want to be able to send the value of this field to a php function such as
$full_informations = get_more_info_from_mail($email)
then I could do something like
$firstname = $full_informations['firstname'];
$lastname = $full_informations['lastname'];
$job = $full_informations['job'];
//...
and make these variables automatically inserted in my mysql DB without asking the user to complete the form (I know how to make that part).
So, again, my question is, how can I get my function to be called with the value of the field after the user has entered an email?
I suppose I'll need some ajax request but I'm not familiar with those at all.
Are you using a mysql database. You can achieve this in php like this:
Put this at the beginning of you page
<?
if (isset($_POST['submit'])) {
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$mail = $_POST['mail'];
$result = mysql_query("SELECT * FROM users WHERE email = $mail");
$row = mysql_fetch_row($result);
$firstName = $row[0]; //FirstName
$lastName = $row[1]; //LastName
$job = $row[2]; //Job
}
?>
You html should look like this:
<form action="" method="POST">
<input type="text" name="mail" />
<input type="submit" value="submit" name="submit" />
</form>
Hope this helps!
With jquery:
<script type="text/javascript">
$(function() {
$('#emails').on('blur',function() {
$.post('/path/to/your/php.php',
{email: $('#emails').val()},
function(json) {
alert('responded with '+json.response);
});
});
});
</script>
Your php script should look like this:
<?php
$email = $_GET['email'];
// make sure you verify the email is in a correct format.
// save it to a database
//if it succeeds:
echo json_encode(array('response'=>'success'));
//if it fails:
echo json_encode(array('response'=>'failure'));
I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.