This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Update database info with onclick button
I have a onclick button which calls a function with php inside of it to query a database. The code works fine separately, but together, it does nothing. After looking through some answers it says I have to place the query database code into a separate PHP file, and somehow call that file on the users onclick ? Is that the best option, and if so, can anyone provide an example of how I would call the PHP database lookup file from an onclick button ? Thanks in advance.
<div onClick="newUser();"
style="position:absolute;display: block; cursor:pointer; top: 100px; left: 600px;">
<img src="assets/invite.png">
</div>
<head>
<script type="text/javascript">
<?php
function newUser(){
// Make a MySQL Connection
$me = json_decode(#file_get_contents('https://graph.facebook.com/me?access_token=' . $cookie['access_token']));
$uid = $me->id;
echo "$uid";
$hostname="";
$username="";
$password="";
$dbname="mpsuserdata";
$usertable="userdata";
$connection = mysql_connect($hostname, $username, $password);
mysql_select_db($dbname, $connection) or die ("Could not connect");
mysql_query("INSERT INTO userdata
(id, name, startdate, enddate, shop) VALUES('11111111' , 'UK', '$startdate' , '$enddate' , 'test' ) ")
or die(mysql_error());
echo "Data Inserted!";
}
?>
</script>
Use AJAX..
AJAX is the very much easy solution for you. you can put JavaScript function on your button on-click event.
and call jquery.ajax function for that. you can now use your php page for execute query for your database.
function ajaxfunc()
{
jQuery.ajax({
type: "GET",
url: "query_page.php",
data: "queryfields",
success: function(html){
// data you want to return on.
}
});
}
i think this makes you happy and satisfied.
this can be done through ajax post/get method for more please go through the link
Related
This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 4 years ago.
I'm trying to send data through AJAX to a PHP file to then upload to my database using SQL. I've already altered my table to allow UTF-8 to be inserted. When I insert using a form it works fine but when using AJAX to send data it won't send it.
For example, I'm trying to send some text and an emoji to a PHP file which then uploads to my database.
I've already got <meta charset="utf-8"> at the top of my page and even added header("Content-Type: text/html; charset=utf-8"); to the page and PHP file as I've seen some other posts mention that but it hasn't worked.
Here is the AJAX function:
$detail = $('#post').text(); //Gets text from div
$.ajax({
url: 'edit.php',
type: 'post',
contentType: 'application/x-www-form-urlencoded;charset=utf-8',
data: {detail: $detail},
datatype: 'html',
success: function() {
console.log($detail);
}});
The $detail is simply the value from a div and all the edit file simply does is UPDATE the table.
When I console.log the data it comes back with text and an emoji but it doesn't insert into my database.
While writing this, I noticed that adding 'application/x-www-form-urlencoded;charset=utf-8' stops the whole process from working but I'm not sure why.
Backend Code for those that asked:
<?php
$host = "hostname";
$user = "user";
$password = "pass";
$db_name = "database";
$tbl_name = "table";
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$detail = $_POST['detail'];
// Add your validation and save data to database
if(strlen($detail) <= 5000) {
$stmt = mysqli_stmt_init($conn);
$sql = "UPDATE $tbl_name SET detail = ?";
if (mysqli_stmt_prepare($stmt, $sql)) {
mysqli_stmt_bind_param($stmt, "s", $detail);
mysqli_stmt_execute($stmt);
}
mysqli_stmt_close($stmt);
}
}
?>
NOTE: This works when I pass it through a form but via AJAX when adding an emoji such as 😂 it doesn't work.
Add mysqli_set_charset($conn, 'utf8mb4'); to all php files after connecting to database.
This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I have a failing PDO Prepared DELETE statement inside a PHP file called with AJAX.
My AJAX call looks like this:
var data = {action: "deleteTask", value: "1"};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: data,
success: function(data) {
alert(data);
},
error: function() {
alert("Something's wrong!");
}
});
My ajax.php looks like this:
<?php
...
function delete(){
$return = "something must be right...";
require('connect.php');
$sql = "DELETE FROM 'tasks' WHERE 'task_id' = ?";
$stmt = $dbcon->prepare($sql);
$stmt->execute(array($_POST["value"]));
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
Here is a sample of connect.php:
<?php
// Configuration
$username = 'me';
$password = '1234';
$server = 'localhost';
$database = 'mydb';
try {
$dbcon = new PDO("mysql:host=$server;dbname=$database",$username,$password);
$dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $er) {
echo 'ERROR: ' . $er->getMessage();
}
?>
A few things that I have already established:
1) My ajax call works fine if I comment out everything related to the PDO statement;
2) My connect.php file works, because I have tested it with standard HTML forms (as opposed to calling it from ajax);
3) there are no typos in the names of the table and the field of the DB;
4) The $_POST["value"] gives the the right value corresponding to the record I am trying to delete.
5) When I set brakepoints on each line related to the PDO, when I am at the line: $stmt->execute(array($_POST["value"])); and I click "Step Into", it jumps straight to the alert("Something's wrong!"); in the Ajax (nothing gets executed in the ajax.php after that line)
I have spent many hours trying to figure out what is wrong with this and read all the posts that exist on the subject, but my problem seems particular, so any help would be much appreciated! Thanks.
You should look into the browser's the Net responce. It should show a SQL error. If you use MySQL your query should look:
DELETE FROM `tasks` WHERE `task_id` = ?
And if it is PostgreSQL:
DELETE FROM "tasks" WHERE "task_id" = ?
Seems like you forgot to add the code:
delete();
Once you will add it, you will actually call the function and not only declare it.
Another option, try and set PDO to print error. http://php.net/manual/en/pdo.errorinfo.php Then you will the error printed back in the console.
I am posting a form to insert values into a database using mysqli, I am getting the following error:
Warning: mysqli::real_escape_string() [mysqli.real-escape-string]: Couldn't fetch mysqli in /home/richa161/public_html/chat/chat.class.php
I have tried wrapping it in an if statement to check for errors coming back from the DB but there are none. Here is my code:
require_once('config.php');
class Chat {
private $mysqli;
//open database connection
function __construct(){
$this->mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DATABASE);
if($this->mysqli->connect_error){
die('error');
} else {
die('ok');
}
}
//insert message to database
public function postMessage($username, $message){
if ($this->mysqli->connect_error) {
die('Connect Error: ' . $this->mysqli->connect_error);
} else {
//make data safe for database
$username = $this->mysqli->real_escape_string($username);
$message = $this->mysqli->real_escape_string($message);
//build query
$query = "INSERT INTO chat (post_date, username, message) VALUES(NOW(),'".$username."','".$message."')";
//execute query and store in $result
$result = $this->mysqli->query($query);
echo $query;
}
}
//close database connection
function __destruct(){
$this->mysqli->close();
}
}
I am grabbing the form data using jQuery and sending it to another file which then uses the classes to call the function required. I do not think the problem is in these files however.. If you think I need to post them I will. Quite sure the error is in the above however.
Connection details are 100% correct..
The jQuery posts values username and message to this page which then calls the class:
require_once('chat.class.php');
session_start();
if(!isset($_SESSION['chat'])){
$_SESSION['chat'] = new chat();
}
$chat = $_SESSION['chat'];
$username = $_POST['username'];
$message = $_POST['message'];
//run function
$chat->postMessage($username, $message);
Starting to think it is the way in which I am posting to my file ajaxRouter.php which is above this text.
index.php contents:
<script type="text/javascript">
$("#chatForm").submit(function(e){
e.preventDefault();
var username = $("input[name='username']").val();
var message = $("input[name='message']").val();
charCount = username.length;
if(!/[^a-zA-Z0-9]/.test(username) && charCount > 2) {
$.ajax({
url: 'ajaxRouter.php',
type: 'post',
data: { 'username' : username, 'message' : message },
success:function(result){
console.log(result);
}
});
} else {
alert("Username must be more than 2 charcters, no special charcters allowed");
}
});
</script>
You are not constructing a mysqli object, the class mysqli_connect does not exist.
You need to change your constructor to:
function __construct(){
$this->mysqli = new mysqli(DB_HOST,DB_USER,DB_PASS,DATABASE);
^^^^^^ You need to construct a `mysqli` object
}
This is also wrong:
$query = "INSERT INTO chat (post_date, username, message) VALUES(NOW(),".$username.",".$message.")";
Assuming that $username and $message are strings, you need to quote them:
$query = "INSERT INTO chat (post_date, username, message)
VALUES(NOW(),'{$username}','{$message}')";
^ ^ ^ ^ here
Edit: You don't have any error handling in your constructor. To see if all mysqli calls execute without problems, you can setup mysqli to throw exceptions when something goes wrong so that you don't have to check manually on each call. To do that, add this to the top of your script:
ini_set('display_errors',1);
error_reporting(E_ALL | E_STRICT);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
Edit 2: You cannot persist your database connection in your session like that. You need to start a new database connection every time the script is started. The most logical solution would be to separate the database operation from the chat class and instantiate that always.
In postMessage(...) you check $this->mysqli->error, which isn't necessarily a connection error (what else is happening between the time the constructor is called and this function is called?). Try checking $this->mysqli->connect_error in __construct and if the connection failed, set $this->mysqli to null. Then you can then check whether or not $this->mysqli is instantiated before you try to use it in other places.
http://php.net/manual/en/mysqli.connect-error.php
http://php.net/manual/en/mysqli.error.php
What you have to check is your DB_HOST,DB_USER,DB_PASS,DATABASE constants.
This error could happen when some of these don't have appropriate values.
Also make sure you quote your values as Fred -ii- pointed:
$query = "INSERT INTO chat (post_date, username, message) VALUES(NOW(),'".$username."','".$message."')";
EDIT:
This is from the manual:
The cryptic "Couldn't fetch mysqli" error message can mean any number
of things, including:
You're trying to use a database object that you've already closed. Reopen your database connection,
or find the call to mysqli_close($db); or $db->close();
and remove it.
Your MySQLi object has been serialized and unserialized for some reason. Define a wakeup function to re-create your database
connection. http://php.net/__wakeup
Something besides you closed your mysqli connection (in particular, see http://bugs.php.net/bug.php?id=33772)
You mixed OOP and functional calls to the database object. (So, you have $db->query() in the same program as
mysqli_query($db)).
This happened to me. The problem occured because I have included two php files ; one for the database connection and another for users' authentication. The users' authentication file itself has the database connection file included. In effect two connections in one php file
I want to display time in the web page every second and update in the MySQL database simultaneously for my project. I tried it with PHP. But the page needs to be refreshed every second to do this. Making a server call every second dosen't seem like a good idea to me. Is there any other way to do this?
<?php
$url1=$_SERVER['REQUEST_URI'];
$username = "root";
$password = "root";
$hostname = "localhost";
date_default_timezone_set('Asia/Calcutta');
$date = date('m/d/Y h:i:s a', time());
echo ("Date: $date");
$dbhandle = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysqli_select_db($dbhandle, "testing") or die("Cannot select database");
$sql = "INSERT INTO data ".
"(date)".
"VALUES ( '$date')";
mysqli_query( $dbhandle,$sql );
header("Refresh: 1; URL=$url1");
?>
You can have an element on the page to both display the date/time and write to the database. Use an interval to trigger ajax calls:
<html>
<body>
<span id="mytime"></span>
<script src="http://www.antradar.com/download/nano.js"></script>
<script>
setInterval(function(){
ajxpgn('mytime','updatetime.php?');
},1000); //update every second
</script>
</body>
</html>
The updatetime.php code would be the same as yours, except that you want to omit the header part.
The ajxpgn function in the Nano Ajax library is similar to the ajax updater function in prototype.js and jQuery, except that if a second request is sent to server and the first request is still in flight for any reason, the first request is canceled to avoid congestion.
I have some jQuery that when you click the save button it triggers a function to grab the HTML matching a selector and post the HTML to save_report.php:
function saveReport() {
$.post('save_report.php', function(data) {
$('.report').html(data);
});
}
$('.save').click(function () {
saveReport();
});
In save_report.php I want to know how i can then save that string to my db.
$report = $_POST['']; # <-- not sure how to post
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports (id, report) VALUES('', $report) ")
or die(mysql_error());
How do I retrieve the POST value in my php file?
Thanks
Couple of things wrong here... The posted code doesn't actually post any data, and the post and html functions are called incorrectly.
So, first I'll grab the html from the .report selector, and store it in a variable. Then I'll post it providing a variable name of 'report'. I added a simple callback that alerts what the web server sends back, which you can remove or change.
function saveReport() {
var data = $('.report').html();
$.post('save_report.php', {'report':data}, function(response) { alert(response); });
}
$('.save').click(function () { saveReport(); });
In your PHP, you would be looking for $_POST['report'] which is how I named the data being posted.
You're not sanitizing any of the input, so basically any random hacker could take over your entire database with SQL injection. At a minimum, after getting $_POST['report'], run it through the mysql_real_escape_string() function.
Most likely you need to change your jQuery code to
function saveReport() {
$.post('save_report.php', {report: $('.report').html(data)} );
}
and php to
$report = $_POST['report']; **<-- not sure how to post**
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
mysql_query("INSERT INTO reports
(id, report) VALUES('', '".mysql_real_escape_string($report)."' ) ")
or die(mysql_error());
Please don't forget to escape the HTML before you put it in your insert query. What you're doing has the potential to go very wrong very fast. I've modified your save_report.php code to fit Fosco's answer. I am now passing the 'optional' $link parameter to all of the mysql_* functions because in general it is a best practice to do so. I've also added some escaping of the value before it is used in your INSERT query; It is important to pass the $link parameter to the mysql_real_escape_string() function so it can properly escape the value.
$report = $_POST['report'];
$link = mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("database", $link) or die(mysql_error());
$report = mysql_real_escape_string($report, $link);
mysql_query("INSERT INTO reports (id, report) VALUES('', '{$report}')", $link)
or die(mysql_error());