Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a MySQL Database but my function is not working. I want to know how many results I get for my database query, but I just get nothing back, not even 0. I also tried $values->num_rows; same result. Do not get back a number... just nothing
My Code:
$values = $database->query("SELECT * FROM `wp_all_import_xml` WHERE name = '$title' AND price = '$price' AND shop = '$shop' AND link = '$link'");
$count_values = mysqli_num_rows($values);
echo "ERROR by detecting Product (More than 1 Row return by SQL!): " .$title. " Preis: " .$price. " Shop: " .$shop. " Link: " .$link. "\t num_rows: " .$count_values. "\n";
How can I get the amount of rows I get returned?
Greetings
The mysqli_num_rows function does work.
The most likely explanation for the observed behavior is an error is occurring and being ignored.
For debugging this, start with making sure error reporting is enabled.
Modify the code to check the return from the query. Verify that it's not returning FALSE, by performing a conditional test.
if ($values = $mysqli->query(...) ) {
// query returned a resultset
} else {
// query returned FALSE
}
If all we need to retrieve is the number of rows, then we can use COUNT(*) in the SELECT list.
if ( $res = $mysqli->query("SELECT COUNT(*) AS cnt FROM ... ") ) {
If the query is successful, then we get a row back, even if the count is zero. And we can easily process the result like we process results from other queries, without the need to muck with num_rows, and worrying about whether the query is buffered or unbuffered, etc.
We're going to assume that $database is a mysqli connection, and not a PDO connection, since the code includes a call to the mysqli_num_rows function. If it's PDO connection, then "num_rows doesn't work".
The code in the question follows the pattern frequently seen in code that is vulnerable to SQL Injection. (In this excerpt, we can't determine if the values of the variables being included in the SQL text are potentially unsafe, so we can't tell if it's vulnerable or not.)
If this was a prepared statement with bind placeholders, then we could tell.
Use prepared statements with bind placeholders. It isn't hard.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have a MySQL column with data looking like this,
I need to convert the column to the JSON format via convert(somecolumn,JSON). However, it seems that I first need to remove the escape symbols (e.g., \"). I did some search and found that mysql_real_escape_string will do the job (from this question).
But if I understand correctly, mysql_real_escape_string is a PHP command. Is there any native MySQL command that do similar thing as mysql_real_escape_string (something like convert(mysql_native_function(somecolumn),JSON))?
Use REPLACE. For harder things REGEXP_REPLACE.
SELECT REPLACE(somecolumn, '\"', '"')
SELECT REGEXP_REPLACE('"..."', '(^"|"$)', '')
The latter will unquote the entire string, as ^ is the start, and $ the end.
BTW I would actually correct all the data in the table once. (After a backup.)
The mysql library is old.. if you really need to use something like it - use mysqli
the mysql_real_escape_string is not as secure as you would think it to be, see this: https://security.stackexchange.com/questions/8028/does-mysql-escape-string-have-any-security-vulnerabilities-if-all-tables-using-l
That said you're much better off by not using any of them but using Php PDO and replacing something like:
$data = [
'name' => $name,
'surname' => $surname,
'sex' => $sex,
];
$sql = "INSERT INTO users (name, surname, sex) VALUES (:name, :surname, :sex)";
$stmt= $pdo->prepare($sql);
$stmt->execute($data);
it will take care of the 'escaping' problems for you.
more examples here: https://phpdelusions.net/pdo_examples/insert
I am wanting to take data from mysql, display it, have users edit this data and then save it to the database. I have all currently working except the saving to the database part. I have been lead to believe that the UPDATE query in mysql is how you get this to work. I put an UPDATE query in place and had no luck. Has anyone here experienced this issue before? I have read several posts here and on perl monks about this issue and can't seem to find an answer that solves my problem. I will put some of my code below. Thanks!
my $dbh=DBI->connect("dbi:mysql:survey_one", "user", "password", { PrintError =>0, RaiseError => 1, AutoCommit => 1}) or die $DBI::errstr;
my $edit_sql = q{UPDATE new_survey SET question = ? WHERE title= ?};
my $sthe = $dbh->prepare($edit_sql);
$sthe->execute($questionedit, $marathon);
$sthe->finish();
I'd like to note that if I were to SET the question column to a string like 'does this work?' I would have success. It's when I try to use user input $questionedit, which is defined as
$questionedit = param('editquestion'); This is where users can edit the question field.
Thanks!
The following are the four possible outcomes:
Nothing happens because the code isn't executed.
An exception is thrown because an error occurred (and RaiseError => 1 was used). The exception will end up being printed to STDERR unless caught.
->execute returns the string 0E0 (which is true, but numifies to zero) because no rows were updated because the WHERE clause didn't match any rows.
->execute returns a positive number indicating the number of rows modified.
Determine which case is applicable, and you'll know how to move forward.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
First post. Please bear with me if formatting isn't one-hundred per-cent. Thanks.
I'm in the process of migrating from an older centos server to one with a more up-to-date Debian 9 operating system and I've run into several program incompatibilities... but it hasn't been all bad. I have the full LAMP stack working and "several databases and their pages" up and running just fine. Unfortunately, I've run into a snag. I'll walk through it...
In my www-accessible perl script, I don't include login details in a publically accessible location. I initiate MySQL like so...
use DBI ;
require "connect.cgi" ;
&my_connect();
In the connection file, I have like this...
sub my_connect {
$dsn = "DBI:mysql:dbmydatabase:localhost" ;
$user_name = 'uMyUser';
$user_pass = 'pMyPassword';
$dbh = DBI->connect($dsn, $user_name, $user_pass, { RaiseError => 1} ) ;
return $dbh;
}
So far, so good. I've checked the connection like so...
if(!$dbh){
die "failed to connect to MySQL database DBI->errstr()";
}else{
print("Connected to MySQL server successfully.\n");
}
... and all appears fine and dandy.
I also call for execution from the connection file, like so...
sub Do_SQL {
$sth = $dbh->prepare($SQL);
$rv = $sth->execute;
return $sth;
}
And for the task -- I want to check for the existence of a record in a database. So I set it up and run it...
$SQL = qq/ SELECT EXISTS(SELECT 1 FROM `table1` WHERE `col1` = '$col1') /;
&Do_SQL;
Trouble is, I'm getting an empty query message.
DBD::mysql::st execute failed: Query was empty at connect.cgi line 54.
I have tried a few variations on the query. For example...
$SQL = qq/ SELECT count(*) FROM `table1` WHERE `col1` = '$col1') /;
$SQL = qq/ SELECT `id` FROM `table1` WHERE `col1` = '$col1') /;
$SQL = qq/ SELECT * FROM `table1` /;
... but the result is the same.
I might be tempted to suggest there is some sort of version incompatibility between old and new set up but I have several other pages with similar configuration working fine. A difference might be that the stuff I have working was backed up and restored from previous databases. Whereas this current problem is the first new database I've created from scratch on the new server.
Interestingly, the queries I note above work on the command line. They do not work within the perl script. I've done several searches but can find nothing to point toward a solution. So here I am seeking the benefit and wisdom of more experience than my own.
Thanks for your insights.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here's how bind_params seem to be preparing sql statements:
stmt = db.prepare( "select * from table where a=? and b=?" )
stmt.bind_params( 15, "hello" )
So in reality inside the stmt, we need to have map/array or something that will eventually map the arguments and create the right stmt. What's the most optimal way of doing this internally? Plus strings need extra precaution I imagine - the above will have to be mapped like "select * from table where a = 15 and b = \"hello\" ".
I looked into SQLite3 and OCI and they seem to be passing these to internal C code.
I am trying to prepare the queries at the client side and send it to the server
If you're trying to do what it sounds like you're trying to do... don't try to do that.
That's not what a prepared statement is (or at least that isn't what it should be).
Your client code should not be trying to interpolate values into the query string in order to generate a "finished" query to send to the server for execution. That is a recipe for disaster, not to mention a false sense of security.
Prepared statements deliver the statement with ? placeholders to the server as-is, where the server "prepares" the statement for execution... and then the client send the parameters to the server ("binding" the parameters) for execution. Doing this, the server will never be confused as to "which part is the SQL" and "which part is the data," making sql injection impossible and making escaping and sanitizing the data unnecessary.
mysql_stmt_bind_param() is used to bind input data for the parameter markers in the SQL statement that was passed to mysql_stmt_prepare(). It uses MYSQL_BIND structures to supply the data. bind is the address of an array of MYSQL_BIND structures. The client library expects the array to contain one element for each ? parameter marker that is present in the query.
— http://dev.mysql.com/doc/refman/5.6/en/mysql-stmt-bind-param.html
If you are not communicating directly with the C-API then you should be calling the methods in your library that expose those same functions to you.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
I can't believe I am having this problem. I've been looking and looking but I can't see what is wrong. I hate this error message.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' poster_ip, message, posted, thread_id INTO posts ' at line 1
mysql_query("INSERT poster, poster_ip, message, posted, thread_id
INTO posts
VALUES (
{$post_info['poster']},
'".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
'".mysql_real_escape_string($post_info['message'])."',
{$post_info['posted']},
{$post_info['thread_id']}") or die (mysql_error());
Your SQL syntax is wrong.
You should be using something similar to:
INSERT INTO posts (poster, poster_ip, message, posted, thread_id) VALUES (...)
Maybe you should look at the doc ;)
Insert Syntax
If you're going to put the column names you should put it after the table name.
Example:
INSERT INTO table (col1, col2) VALUES (val1, val2)
Looks like a good opportunity to practice some debugging techniques. Try building the string you are passing to the function and assigning it to a variable, then echoing that variable to see what it is you are actually passing to the function. You can learn a lot that way about why you are getting errors. Also, it would help to know the data types of the columns you are inserting values into.
I have written this code to show you why arrays are useful for query generation and less likely to make a syntax error if you need to add more fields in future.
$fields = array('poster, poster_ip, message, posted, thread_id'); // Our fields
$table = 'posts'; // Our table name
$values = array(
$post_info['poster'],
$_SERVER['REMOTE_ADDR'],
$post_info['message'],
$post_info['posted'],
$post_info['thread_id']
);
$values = array_map('mysql_real_escape_string', $values); // Secure all inputs
// Generate query
$query = "INSERT INTO $table (" . implode(',', $fields) . ") VALUES ('" . implode("','", $values . "')";
// Run query
$result = mysql_query($query) or die('query error: ' . mysql_error());