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.
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.
I read most of the posts related to my question but none can resolve my simple issue.
I am using PHP and MySQLi to retrieve data from my server.
In my Database I have a one-dimensional table (i.e. one column only) and I want to put its data inside an array.
Until now I was using JSON to hold the data from my server.this is my code:
<?php
include 'ChromePhp.php';
$con=mysqli_connect("197.168.240.100","jsoncloud","nuahyu,hs","json");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
ChromePhp::warn('Failed to connect to MySQL');
}
$sql="SELECT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = array();
while ($row = mysqli_fetch_all($result,MYSQLI_ASSOC)) {
$rows[] = $row[0];
}
echo json_encode($rows);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>
My final goal is to echo the array back so I can use it with Ajax in another JS file
in the other JS file I have the following code:
$.ajax({
type: 'POST',
url: 'js/SQLusersstreets.php',
dataType: 'json',
success: function(jsonData) {
console.log(jsonData);
},
error: function() {
alert('Error loading SQLusersstreets.php from GoogleMapsCode.js');
}
});
This is my output when I open the browser's debugger:
I am trying to return a simple array, what am I doing wrong?
Change mysqli for PDO
Assuming a connection is already established, you will need only one line of code:
echo json_encode($pdo->query("SELECT `street` FROM `users`")->fetchAll(PDO::FETCH_COLUMN));
but if you prefer to write a lot of code, then change fetch_all to fetch_assoc
try this, if this is what you are asking about:
for($i=0;$i<sizeof($rows);$i++){
echo $rows[$i]['id']; //for example
}
mysqli_fetch_all is a shortcut for while($row = mysqli_fetch) {}, so you can skip the while cycle.
$sql="SELECT DISTINCT `street` FROM `users` ";
$result=mysqli_query($con,$sql);
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
echo json_encode(array_map(function($i) { return $i['street']; }, $rows));
See the documentation here for more examples http://php.net/manual/en/mysqli-result.fetch-all.php
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
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
I am using a jQuery AJAX request to a page called like.php that connects to my database and inserts a row. This is the like.php code:
<?php
// Some config stuff
define(DB_HOST, 'localhost');
define(DB_USER, 'root');
define(DB_PASS, '');
define(DB_NAME, 'quicklike');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die('ERROR: ' . mysql_error());
$sel = mysql_select_db(DB_NAME, $link) or die('ERROR: ' . mysql_error());
$likeMsg = mysql_real_escape_string(trim($_POST['likeMsg']));
$timeStamp = time();
if(empty($likeMsg))
die('ERROR: Message is empty');
$sql = "INSERT INTO `likes` (like_message, timestamp)
VALUES ('$likeMsg', $timeStamp)";
$result = mysql_query($sql, $link) or die('ERROR: ' . mysql_error());
echo mysql_insert_id();
mysql_close($link);
?>
The problematic line is $likeMsg = mysql_real_escape_string(trim($_POST['likeMsg']));. It seems to just return an empty string, and in my database under the like_message column all I see is blank entries. If I remove mysql_real_escape_string() though, it works fine.
Here's my jQuery code if it helps.
$('#like').bind('keydown', function(e) {
if(e.keyCode == 13) {
var likeMessage = $('#changer p').html();
if(likeMessage) {
$.ajax({
cache: false,
url: 'like.php',
type: 'POST',
data: { likeMsg: likeMessage },
success: function(data) {
$('#like').unbind();
writeLikeButton(data);
}
});
} else {
$('#button_container').html('');
}
}
});
All this jQuery code works fine, I've tested it myself independently.
Any help is greatly appreciated, thanks.
Are you 1000% sure that $_POST["likeMsg"] actually contains something?
As for mysql_real_escape_string() returning an empty value, the manual says there is only one situation where that can happen:
Note: A MySQL connection is required before using mysql_real_escape_string() otherwise an error of level E_WARNING is generated, and FALSE is returned. If link_identifier isn't defined, the last MySQL connection is used.
this doesn't seem to be the case here though, as you do have a connection open. Strange.
As the other answers don't make clear what exactly to do, here's my:
When you do
$db_connection = new mysqli($SERVER, $USERNAME, $PASSWORD, $DATABASE);
you need to escape like this:
$newEscapedString = $db_connection->real_escape_string($unescapedString);
NOTE: Because people are downvoting this (WTF!?), here's the official page of the official php manual that says EXACTLY what i have posted: real_escape_string # PHP Manual.
For people who might be finding this again now, I just ran into this problem as I'm migrating from PHP5 to PHP7. I'm changing from
string mysql_real_escape_string(string $unescaped, [resource $link = NULL])
to:
string mysqli_real_escape_string(mysqli $link, string $escapestr)
So, in other words, the database $link is no longer optional and moves to the first argument position. If left out, it returns an empty string, without an error, apparently.
Do a var_dump of $_POST['likeMsg'], and a var_dump of $likeMsg. That gives you information on what goes wrong.
mysql_real_escape_string() will return blank response if you have not made connection to database ...