SQL query syntax error, negative number not possible? - php

I receive the following error, the error contains a SQL syntax problem. I would not know what the problem is because everything seems fine. I can see a negative number in $range_start (-4). What would be the problem? Should I add anything at the negative number in the SQL query?
(It's a pagination and it works fine in other SQL queries)
Thanks in advance.
Error:
Array
(
[0] => 42000
[1] => 1064
[2] => 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 ''4'' at line 1
)
Code:
$getPostsByCategory = $this->db->prepare("SELECT * FROM articles WHERE category = :category ORDER by date_created DESC LIMIT " . $range_start . ", " . $range_end . "");

The LIMIT keyword specifies that you want a subset of the elements. $range_start is the offset, that is, the first index of the result you want, while $range_end is the number of elements you want. As a result, both of these need to be positive integers, so $range_start cannot be negative, as you cannot load the elements, starting from the -4th.

Strings need to be encapsulated by either a quote or apostrophe depending on whether your string was constructed with quotes or apostrophes.
In this case, I would recommend the following:
'" . $range_start . "', '" . $range_end . "'
Note the use of apostrophe's before and after.

Related

Full text search returning to many results

I need to search a text column for the occurrence of certain words in the column.
For instance as an example the column contents may look like:
KIT: TYPE WELD NECK ORIFICE FLANGE, CONSISTING OF TWO FLANGES WITH
JACK SCREWS BUT WITHOUT BOLTS AND GASKETS, RATING CLASS 600, RAISED
FACE, BORE TO MATCH .312 IN WALL, MATERIAL FORGED 304 STAINLESS STEEL
ASTM-A182 GRADE F304, SPECIFICATION: SP-50-13 REV: 1
Now the user needs to enter into a textbox for instance the following:
ASTM-A182 F304 WELD NECK
Currently I use this code:
$sql = "SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST ('" . $ldisc . "' IN NATURAL LANGUAGE MODE);";
But most records returned (it returns hundreds of records) don't contain all the search terms entered in the text field.
How can I fine tune this full text search (or use another method) to give me a better result more closely to what was entered?
EDIT:
Table type:
EDIT 2:
It is working now, added this code:
if ($ldisc != "") {
$parts = explode(" ", $ldisc);
$tempSQL = "SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST (" . "'";
for ($i = 0; $i < count($parts); $i++) {
$tempSQL = $tempSQL . '+' . $parts[$i] . ' ';
}
$tempSQL = $tempSQL . "' IN BOOLEAN MODE);";
$sql = $tempSQL;
$result = mysqli_query($con, $sql);
}
And changed the minimum word length to 1.
This question sounds like basically what you're looking for: MySQL fulltext search - Only results that contain all words
NATURAL LANGUAGE MODE by its nature returns approximate matches. To match all words in BOOLEAN MODE, you must add a + in front of every required word. For example,
MATCH (ldisc) AGAINST ('+ASTM-A182 +F304 +WELD +NECK' IN BOOLEAN MODE)
You'll have to split the input string and add the + signs. How to do that is left as an exercise to the programmer. =)
Change it to boolean mode
"SELECT * FROM commtable WHERE MATCH (ldisc) AGAINST ('" . $ldisc . "' IN BOOLEAN MODE);";
Another thing is to keep an eye on ft_min_word_length

How to assign a string value to an index of php array?

I have the following error;
Note: Array to string conversion in [file_path] on line 919
which relates to this line of code where I'm trying to assign this string as a value in an array
$contents[11] = "$hours:$minutes:$seconds\n$ca_1[remaining_time]\n$h:$m:$s";
Why am I getting this error, and how do I resolve it?
It's a bad practice to interpolate string this way because it makes the code very difficult to read, so you should rather use "{$h}" instead of "$h".
As Terminus mentioned in comments, depending on the PHP version,
echo "$ca_1[remaining_time]"
Does not necessarily give a
PHP Notice: Use of undefined constant
Like echo $ca_1[remaining_time] would. But since that didn't work for you, you'd better quote that like ['remaining_time'].
You might also find some interesting things on this topic here.
Second, use curvy braces to explicitly tell what you want to insert:
$contents[11] = "$hours:$minutes:$seconds\n{$ca_1['remaining_time']}\n$h:$m:$s";
This really improves readability.
Try:
$contents[11] = $hours . ':' . $minutes . ':' . $seconds + "\n" . $ca_1['remaining_time'] . "\n " . $h . ':' . $m . ':' . $s";
If this still fails, check your variables. Maybe one of them is an array!?

Submit timestamp to mysql

I am trying to add a timestamp to my database when I update a form, and for reason that I do not know, I am getting an error... and when just trying to insert the year, month, day I get "1988" inserted into my database. I use a similar timestamp elsewhere on the same site and it works fine. What am I doing wrong?
Note: yes I know I should be using mysqli and I'm vulnerable to sql injection. I plan on converting the entire site later in the year.
$homeScore = ((strlen($game['homeScore']) > 0) ? $game['homeScore'] : 'NULL');
$homeOdds = (str_replace("\xBD", ".5", $homeScore));
$visitorScore = ((strlen($game['visitorScore']) > 0) ? $game['visitorScore'] : 'NULL');
$visitorOdds = (str_replace("\xBD", ".5", $visitorScore));
$odds_timestamp = date("Y-m-d g:i:s A");
$sql = "update " . $db_prefix . "schedule ";
$sql .= " set odds_timestamp = " . $odds_timestamp . ", homeOdds = " . $homeOdds . ", visitorOdds = " . $visitorOdds . "";
$sql .= " where gameID = " . $game['gameID'];
mysql_query($sql) or die('Error updating odds: ' . mysql_error());
You have missing (single) quotes " . $odds_timestamp . "
that will need to be '" . $odds_timestamp . "' since it will contain characters that MySQL will complain about... being hyphens.
That is a string.
Now, if any of your other variables are also strings, they too need to be quoted as shown.
I.e.: '" . $string . "' as opposed to " . $integer . "
More on string literals:
https://dev.mysql.com/doc/refman/5.0/en/string-literals.html
Pay attention to Riggs' comments, one of which being:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format"
Using a VARCHAR won't fix it, as it still considered as a string literal for the column.
New comments by Riggs:
"You would be best advised to make the datatype a DATETIME or TIMESTAMP as if you keep the VARCHAR it will make the data much more difficult to process later. Just change the date() to produce a legal MYSQL data format. You can always add the AM/PM when you present the date time to any user. VARCHAR date/time will really mess with your selection criteria later as well. Remember - Database for DATA, Browser for PRESENTATION"
You can use MySQL's NOW() function, which returns current datetime.
Without error message, Its difficult to say something.
or if you can print your query it will be helpful.
but try with.
odds_timestamp = '" . $odds_timestamp . "'
to make it explicit string.
Try adding a timestamp column in the database table with an on update set current timestamp clause.
Heres a simple example from MySQL Documentation:
CREATE TABLE t1 (
ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
Should take care of it and cut out the middle man. Win-win.

Query returns different (no) results when using a variable

I have two select queries returning different results as follows:
This query returns 29 rows:
SELECT SQL_CALC_FOUND_ROWS `last`,`first`,`mate`,`address`
FROM `homeownersnew`
WHERE `last` LIKE "s%" AND
`address` != ""
LIMIT ' . (($pagination->get_page() - 1) * $records_per_page) . ', ' . $records_per_page . '';
This query uses a variable to attempt to accomplish the same results but returns 0 rows:
#$last = "s%";
SELECT SQL_CALC_FOUND_ROWS `last`,`first`,`mate`,`address`
FROM `homeownersnew`
WHERE `last` LIKE "$last" AND
`address` != ""
LIMIT ' . (($pagination->get_page() - 1) * $records_per_page) . ', ' . $records_per_page . '';
I'm sure I am overlooking something but am unable to find the problem.
'single quoted strings are not interpolated'
The most important feature of double-quoted strings [that is not found in single-quote strings] is the fact that variable names will be expanded. See string parsing for details.
Consider this trivial example which shows the issue, mainly that the query literally used LIKE "$last":
$hello = "world";
echo "Hello $hello!"; // => Hello world!
echo 'Hello $hello!'; // => Hello $hello!
The correct solution in this case is to use parameterized queries. It solves the string interpolation issue, cleans up the code, and prevents SQL injection or unexpected data from corrupting queries.

What's wrong with this php code? im trying to concatenate

$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '{$birthmonth}'. "-" .'{$birthday}'. "-" .'{$birthyear}'");
You shoudn't use dots into the string.
But much better way is avoid to inject variables into the strings and use explicit concats:
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '" . $birthmonth . "-" . $birthday . "-" . $birthyear . "'");
Try to concatenate your variables inside your quotes as follow
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '".$birthmonth . "-" . $birthday . "-" . $birthyear."');
As side note i would advise you to switch to either PDO or mysqli since mysql_* api are deprecated and soon will be no longer mantained
From the MYSQL documentation on the Date type:
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
So there is a good chance that your query is not getting you what you want since you are searching based on an incorrectly formatted date. What you want, instead, along with correctly formatted PHP, is:
$result = mysql_query("SELECT * FROM `deceased` WHERE `birthdate` = '$birthyear-$birthmonth-$birthday'");

Categories