mysql_real_escape_string() just makes an empty string? - php

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 ...

Related

PHP: json_encode() doesn't show anything with multidimensional array

I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.
This is my code:
<?php
$servername = "localhost:3036";
$username = "example_user";
$password = "example_password";
$conn = mysql_connect($servername, $username, $password);
if(! $conn) {
die("Could not connect: " . mysql_error());
}
$sql = "SELECT * FROM table_name";
mysql_select_db("database_name");
$retval = mysql_query($sql, $conn);
if(! $retval) {
die("Could not get data: " . mysql_error());
}
while($row = mysql_fetch_assoc($retval)) {
$output[]=$row;
}
print(json_encode($output));
mysql_close($conn);
?>
This just gives a blank page as output (error messages are set to display).
However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.
This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.
User #Joni led me to the solution.
Adding mysql_set_charset("utf8") fixed my issue.
As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.
Try
echo json_encode($output) ;
It seems you have some utf8 character in your result set
add this statement before running your query
mysql_query('SET CHARACTER SET utf8');
Update
"mysql"
to
"mysqli"
and add
mysqli_set_charset($variável_de _conexão, 'utf8');
below the connection variable

PHP PDO prepared delete statement with MySQL fails inside Ajax call [duplicate]

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 have this error: Couldn't fetch mysqli, with no database errors

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

cannot get a connection to MySQL in php

I have this simple code:
<?php
//Open the mySQL connection
$conn_string = "'localhost', 'Vale', 'test'";
$dbh = mysql_connect($conn_string);
//Check that a connection with the DB has been established
if (!$dbh)
{
die("Error in MySQL connection: " . mysql_error());
}
...
And I get the error: Error in MySQL connection: php_network_getaddresses: getaddrinfo failed: The requested name is valid, but no data of the requested type was found.
I cannot figure out what the problem is, I have been google-ing but all the suggestions have failed (tried 127.0.0.1 instead of localhost, 127.0.0.1:3306, etc.)
I have code that works with postgre, but I need to use mysql, and I am trying to modify it, but I cannot pass the first line and get a connection. Any suggestion, please? Thank you!
mysql_connect doesn't take a comma seperated string. It takes 3 individual strings.
Change it to this:
$dbh = mysql_connect($server, $mysql_user, $password);
If you absolutely have a comma separated string, and can't get around this, you can split the string like this:
$config = str_replace("'", '', $conn_string); // replace the quotes.
$config = preg_split('/,/', $conn_string); // split string on ,
if($config != $conn_string) { // make sure this returned an array
count($config) === 3 OR die("Invalid database configuration string");
$dbh = mysql_connect($config[0], $config[1], $config[2]);
if(FALSE === $dbh) {
die("Coult not connect: " . mysql_error());
}
}
You might want to consider MySQLi, instead of MySQL.
<?php
$dbh=mysqli_connect("localhost","Vale","Password","test"); /* Vale is your username? And the name of your database if test, right? And your Username's Password is blank? */
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
?>
As other users have pointed out mysql_connect expects the database, username, and password as separate arguments rather than a single string.
I think another highly important issue to point out is that this particular extension is deprecated.
Please see: http://uk1.php.net/function.mysql-connect
A better solution would be to use mysqli_connect: http://uk1.php.net/manual/en/function.mysqli-connect.php
$db = mysqli_connect( 'localhost', 'Vale', 'test', 'yourDatabaseName' );
mysql_connect requires three argument not single string
$dbh = mysql_connect('localhost', 'Vale', 'test');

mysql vs mysqli config file and queries

I need start using the mysqli extension but I'm finding all kinds of conflicting info depending on how all the info is that I'm trying to use.
For example, my header connects to a 'config.php' file that currently looks like this:
<?php
$hostname_em = "localhost";
$database_em = "test";
$username_em = "user";
$password_em = "pass";
$em = mysql_pconnect($hostname_em, $username_em, $password_em) or trigger_error(mysql_error(),E_USER_ERROR);
?>
But when I go to php.net I see that I should be using this but after updating everything I get no database.
<?php
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
$mysqli = new mysqli("127.0.0.1", "user", "password", "database", 3306);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
?>
I also went through and added an "i" to the following code in my site and again no luck:
mysql_select_db($database_em, $em);
$query_getReview =
"SELECT
reviews.title,
reviews.cover_art,
reviews.blog_entry,
reviews.rating,
reviews.published,
reviews.updated,
artists.artists_name,
contributors.contributors_name,
contributors.contributors_photo,
contributors.contributors_popup,
categories_name
FROM
reviews
JOIN artists ON artists.id = reviews.artistid
JOIN contributors ON contributors.id = reviews.contributorid
JOIN categories ON categories.id = reviews.categoryid
ORDER BY reviews.updated DESC LIMIT 3";
$getReview = mysql_query($query_getReview, $em) or die(mysql_error());
$row_getReview = mysql_fetch_assoc($getReview);
$totalRows_getReview = mysql_num_rows($getReview);
And here's the only place on my display page that even mentions mysql so far:
<?php } while ($row_getReview = mysql_fetch_assoc($getReview)); ?>
I did see something at oracle that another stackoverflow answer pointed someone to that updates this stuff automagically, but I have so little code at this point it seems like overkill.
Adding an i to any mysql function won't make it a valid mysqli function. Even if such function exists, maybe the parameteres are different. Take a look here http://php.net/manual/en/book.mysqli.php and take some time to check mysqli functions. Maybe try some examples to become familiar with the way things work. I also reccomend you to choose either object oriented code, either procedural. Don't mix them.
I just made the switch to mysqli lately, took me a few hours to wrap my head around it. It works well for me, hope it will help you out a bit.
Here the function to connect to the BD:
function sql_conn(){
$sql_host = "localhost";
$sql_user = "test";
$sql_pass = "pass";
$sql_name = "test";
$sql_conn = new mysqli($sql_host, $sql_user, $sql_pass, $sql_name);
if ($sql_conn->connect_errno) error_log ("Failed to connect to MySQL: (" . $sql_conn->connect_errno . ") " . $sql_conn->connect_error);
return $sql_conn;
}
This will return a Mysqli Object that you can use to make you request afterward. You can put it in your config.php and include it or add it at the top of your file, whatever works the best for you.
Once you have this object, you can use it to make your query against the object like so: (in this case, if an error came up it will be outputted in the error_log. I like having it there, you can echo it instead.
//Use the above function to create the mysqli object.
var $mysqli = sql_conn();
//Create the query string (truncated for the example)
var $query = "SELECT reviews.titl ... ... ted DESC LIMIT 3";
//Launch the query on the mysqli object using the query() method
if(!($results = $mysqli->query($query))){
//It it fails, log the error
error_log(mysqli_error($mysqli));
}else{
//Manipulate your data.
//here it depends on what you retunr, a single value, row or a list of rows.
//Example for a set of rows
while ($record = $results->fetch_object()){
array_push($array, $record);
}
}
//Just to show, this will output the array:
print_r($array);
//Close the connection:
$mysqli->close();
So basically, in mysqli, you create an object and use the method to work your way out.
Hope this helps. Once you figured it out, you will most likely enjoy mysqli more that mysql. I did anyway.
PS: Please note that this was copy/pasted from existing, working code. Might have some typo, and might forgot to change a var somewhere, but it's to give you an idea of how mysqli works. Hope this helps.

Categories