AJAX post to php - php

Although i have followed the sample code from http://api.jquery.com/jQuery.post/ and of course Stackoverflow i couldnt find a solution to my problem.
I have a toggle image in html which everytime a user clicks on it,changes the image and update the column in the DB.Here is the code:
HTML
<input type="image" src="smileys/heart.gif" class="play" onclick="toggle(this,'<?php echo $ida;?>')"/>
AJAX
function toggle(el,al){
if(el.className=="play")
{
el.src='smileys/lol.gif';
el.className="pause";
$.post("update.php", { "hr": 1, "ida": al } );
}
else if(el.className=="pause")
{
el.src='smileys/heart.gif';
el.className="play";
$.post("update.php", { "hr": 0, "ida": al } );
}
console.log(al);
return false;
}
update.php
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$heart=$_GET["hr"];
$ida=$_GET["ida"];
$con = mysql_connect($host,$user,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE tablename SET heart='$heart' WHERE id='$ida'");
?>
The toggle function works well but the DB is not updated when a user clicks and the image.
I believe it has to do with the $.post function,not sending correctly the data to the php.
BTW if i do
http://domain.com/update.php?hr=1&ida=127
it works.
NOTE: I am using mysql and not PDO only for this example.
...and yes my code is messy and ugly,still learning.
Any help?
Thanks

Well, it's a _POST request and not an _GET, so, to capture its values you need to use $_POST instead $_GET.
Also, as i noticed, there's and _GET link, so you need to change your $.post with $.get.

Related

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Login issue with mySQL no database selected

I'm a beginner of PHP coding which I face this problem and I tried to fix it.
I have search through stackoverflow for answers but it stills no good.
This is my Login form.php file
<form name = 'LoginForm' method = 'POST' action = 'verifyUser.php'>
<br />
E-MAIL: <input type = "Textbox" Name = "App_Email"><br><br>
PASSWORD: <input type = "password" Name = "App_Password"><br><br>
<input type = 'Submit' name = 'Login' value = 'Log in'><br><br>
</form>
This form will goes to verifyUser.php and these are codes
include ('DBconnect.php');
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if($username=='' || $pass=='') {
header("Location:login.php?id=Some fields are empty");
}
$result = mysql_query("SELECT * FROM applicant_acct ");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if ($username==$row['App_Email']) {
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.html?id=$username");
} else {
header("Location:login.php?id=username or your password is incorrect. Please try again");
}
}
}
And final DBconnect.php
<?
$dbc = mysql_connect('localhost','root','root') OR die('Wrong Connection!!!!!!!');
mysql_select_db('onlinerecruitment') OR die ('Cannot connect to DB.');
?>
I really have no idea why it shows "Query Failed: No database selected"
I think the problem is in verifyUser.php but have no idea where.
And another thing, after I logged in how can I generate the text "Welcome - "Username"" and provide them the logout button?
Please help.
Thank you.
Generally you may want to research a graphical user interface such as XAMPP or MySQL workbench until you are more comfortable with Database systems.
Here it seems like most of the improvements can be made in you DBConnect.php file. You are beginning and I can appreciate that. Consider something along the following lines that incorporates additional the security of PDO:: static calls.
<?php
public function _dbconnect($hostpath, $database, $username, $password){
try {
$this->conn = new PDO("mysql:host = {$hostpath};
dbname - {$database};
charset = utf8",
$username,
$password);
} else { exit(); }
?>
If this particular code block doesn't help I would highly recommend that you continue by investigating PDO:: calls.
<?php
include ('DBconnect.php');
if(isset($_POST['Login'])){
$username = $_POST['App_Email'];
$pass = $_POST['App_Password'];
if(empty($username) || empty($pass) || ctype_space($username) || ctype_space($pass)){
header("Location:login.php?error=1");
} else {
$result = mysql_query("SELECT * FROM applicant_acct");
if(!$result) {
die("Query Failed: ". mysql_error());
} else {
$row = mysql_fetch_array($result);
if($username==$row['App_Email'] && $pass==$row['App_Password']) {
header("Location: index.php?id=$username");
} else {
header("Location:login.php?error=0");
}
}
?>
I have a lot to say about your code.
Use isset function . This function check if something was done.
Check your database details again. Maybe you wrote something
wrong (misclick or something)
Use $_GET['error'] to get errors. I set 1 = for empty characters and 0 for 0 match between database and inputs.
Use sessions for after login message. You can also use Session to handle your errors.
EDIT: I recommend you to start to learn MySQLi or PDO.

Isset function not working

I'm working on PHP at the moment.
I have a form seen below with a submit button.
I then created a function below also.
As you can see the first thing the function does is checked the submit button is pressed, but it goes into this if upon loading the page(i don't need to press the button), and it out puts the "Entry Submitted" p tag autmoatically, where it shouldn't even be entering the first if statement.
Any help appreciated,
<p>
<input type="submit" name="Submit" id="Submit" value="Submit" tabindex="100"/>
<br />`enter code here`
</p>
</form>
<?php
if (isset($_POST['Submit'])){
$conn_error = 'Could not connect.';
$mysql_host = 'localhost';
$mysql_user = 'auser';
$mysql_pass = 'auser';
$mysql_db = 'ourwebdb';
// Connect to database
if (!#mysql_connect($mysql_host, $mysql_user, $mysql_pass) || !#mysql_select_db($mysql_db)) {
die ($conn_error);
}else {
//echo 'Connected';
// Perform database insert
$name = $_POST["Name"];
$email = $_POST["email"];
$teamSupported = $_POST["radioGroup"];
$comment = $_POST["comment"];
$query = "INSERT INTO visitors (Name, Email,[Supported Team], Comment)
VALUES ('{$name}', '{$email}', '{$teamSupported}', '{$comment}')";
$result = mysql_query($query);
if ($result) {
// Success
$id = mysql_insert_id();
echo '<p> Entry Submitted</p>';
// Do something
} else {
die ("Database query failed. ". mysql_error());
}
}
}
mysql_close();
Change your 1st PHP line
if (isset($_POST['Submit'])){
to
if (isset($_POST['Submit']) && $_POST['Submit']=='Submit' ){
there is nothing wrong in your code (except cut out portion of form). so there is two possible scenario 1. you are refreshing browser url with re-submit 2. there are some onload javascript/jquery function which submit the page (form.submit()..)
Solution for 1. is easy just open the url in new tab. for scenario 2. you need to check Or submit your full code here

failure to post PHP update to MySQL

i have a button i am trying to get where if i click it it updates the column 'gorg' in the table users to giver according to the current user (session) logged in. Everytime i click the button i get
Access denied for user 'root'#'localhost' (using password: NO)
Here is the top of the php page (BTW i am 100% positive my DB Connection info is correct)
<?php
session_start();
include('src/sql_handler.php'); //this is where my DB Connection info is located
include('src/facebook_handler_core.php');
if(isset($_POST['submitgiver'])) {
$query = "UPDATE users SET gorg='giver' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'";
$result = mysql_query($query) or die(mysql_error());
}
{
if(isset($_SESSION['gorg'])=="Giver")
{
header('Location: picktreetype.php');
}
else if(isset($_SESSION['gorg'])=="Gatherer")
{
header('Location: gatherermap.php');
}
}
?>
and now for the html
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="submitgiver" value="Giver">
</form>
UPDATE:
heres the SQL_HANDLER
<?php
class MySQL_Con {
private $host = 'localhost',
$user = 'fruitfo1_admin',
$pass = 'password',
$db = 'fruitfo1_fruitforest',
$_CON;
function MySQL_Con() {
$this->_CON = mysql_connect($this->host, $this->user, $this->pass);
if(!$this->_CON)
die(mysql_error());
else {
$select_db = mysql_select_db($this->db);
if(!$select_db)
die('Error Connecting To Database'.mysql_error());
}
}
function End_Con() {
mysql_close($this->_CON);
}
}
?>
Apparently your connection setup doesn't include a password. Please post the sql_handler (WITH OBFUSCATED password) to be able to debug further.
If you're 100% positive it's correct, as you're saying, you can try explicitly passing sql handle to mysql_query.
Another note, mysql_* are deprecated, you really should consider switching to either mysqli or PDO.
Also, using root user for ANY kinds of web-applications is a no-no.
Your DB doesn't have a password. Try this
private $host = 'localhost',
$user = 'fruitfo1_admin',
$pass = '',
$db = 'fruitfo1_fruitforest',
$_CON;
i found my issue, it did have to do with exactly what i thought it was. heres my updated code
if(isset($_POST['submitgiver'])) {
$mysql_hostname = "localhost";
$mysql_user = "fruitfo1_admin";
$mysql_password = "password";
$mysql_database = "fruitfo1_fruitforest";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Could not connect database");
mysql_select_db($mysql_database, $bd) or die("Could not select database");
$query = "UPDATE users SET gorg='giver' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'";
$result = mysql_query($query) or die(mysql_error());
}
basically that IF statement that was attempting to POST wasnt linking back to my handler, so i placed the SAME db connection from the handler and carried it over inside the if isset statement and it worked!

PHP database selection issue

I'm in a bit of a pickle with freshening up my PHP a bit, it's been about 3 years since I last coded in PHP. Any insights are welcomed! I'll give you as much information as I possibly can to resolve this error so here goes!
Files
config.php
database.php
news.php
BLnews.php
index.php
Includes
config.php -> news.php
database.php -> news.php
news.php -> BLnews.php
BLnews.php -> index.php
Now the problem with my current code is that the database connection is being made but my database refuses to be selected. The query I have should work but due to my database not getting selected it's kind of annoying to get any data exchange going!
config.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "test";
?>
database.php
<?php
class Database {
//-------------------------------------------
// Connects to the database
//-------------------------------------------
function connect() {
if (isset($dbhost) && isset($dbuser) && isset($dbpass) && isset($dbname)) {
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die("Could not connect: " . mysql_error());
$selected_db = mysql_select_db($dbname, $con) or die("Could not select test DB");
}
}// end function connect
} // end class Database
?>
News.php
<?php
// include the config file and database class
include 'config.php';
include 'database.php';
...
?>
BLnews.php
<?php
// include the news class
include 'news.php';
// create an instance of the Database class and call it $db
$db = new Database;
$db -> connect();
class BLnews {
function getNews() {
$sql = "SELECT * FROM news";
if (isset($sql)) {
$result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error());
}
return $result;
}
?>
index.php
<?php
...
include 'includes/BLnews.php';
$blNews = new BLnews();
$news = $blNews->getNews();
?>
...
<?php
while($row = mysql_fetch_array($news))
{
echo '<div class="post">';
echo '<h2> ' . $row["title"] .'</h2>';
echo '<p class="post-info">Posted by | <span class="date"> Posted on ' . $row["date"] . '</span></p>';
echo $row["content"];
echo '</div>';
}
?>
Well this is pretty much everything that should get the information going however due to the mysql_error in $result = mysql_query($sql) or die("Could not execute query. Reason: " .mysql_error()); I can see the error and it says:
Could not execute query. Reason: No database selected
I honestly have no idea why it would not work and I've been fiddling with it for quite some time now. Help is most welcomed and I thank you in advance!
Greets
Lemon
The values you use in your functions aren't set with a value. You likely need to convert the variables used to $this->dbName etc or otherwise assign values to the variables used.
Edit for users comment about variables defined in config.php:
You really should attempt to get the data appropriate for each class inside that class. Ultimately your variables are available to your entire app, there's no telling at this point if the variable was changed by a file including config.php but before database.php is called.
I would use a debugging tool and verify the values of the variables or just var_dump() them before the call.
Your Database class methods connect and selectDb try to read from variables that are not set ($dbhost, $dbname, $con, etc). You probably want to pass those values to a constructor and set them as class properties. Better yet, look into PDO (or an ORM) and forget creating your own db class.

Categories