Error received from database was #1064 - PHP & MySQL - php

I have a simple MySQL query that I use in PHP but it gives me this error;
Database query failed. Error received from database was #1064: 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 'NULL' at line 3 for the query: SELECT *
FROM mantis_user_table
WHERE email LIKE '%me%'.
$t_user_table = db_get_table( 'mantis_user_table' );
$temp_mail = '%' . $p_email . '%';
$query = "SELECT * FROM $t_user_table WHERE email LIKE '{$temp_mail}'";
$result = db_query_bound( $query, Array( $p_realname ) );
The thing I can not understand is, when I run it in phpmyadmin, it gives me the correct values.
So can you please help me with this situation ?
Thank you
EDIT :
This is the code that I use while editing :
$File = "c:/YourFile.txt";
$Handle = fopen($File, 'w');
$Data = $query;
fwrite($Handle, $Data);
fclose($Handle);
Here you can see the query that I get when I write :
SELECT * FROM mantis_user_table WHERE email LIKE '%meh%'
And this query normally gives me some results in phpmyadmin , now I dont have any result on web site
And if you want this is the rest of the code that returns the id of the selected item:
$result = db_query_bound( $query, Array( $temp_mail ) );
if( 0 == db_num_rows( $result ) ) {
return false;
} else {
$row = db_fetch_array( $result );
user_cache_database_result( $row );
return $row['id'];
}

try making
$query = 'SELECT * FROM $t_user_table WHERE email LIKE "{$temp_mail}"';
(some versions of mysql don't recognize ' symbol)

Related

sqlsrv_query not returning anything

I am trying to run a sqlsrv_connect SELECT query, and I am having issues getting any information back. No matter what query I run, sqlsrv_num_rows always returns a null value. I have verified that my queries are correct in SQL Server Management studio.
Some sample code:
$connection_info = array("UID"=>"uid", "PWD"=>"pwd", "Database"=>"db");
$c = sqlsrv_connect("tcp:hostname", $connection_info);
if (!$c) {
die(0);
}
$sql = "QUERY";
$result = sqlsrv_query( $c, $sql );
$row_count = sqlsrv_num_rows( $result );
echo $sql . $row_count;
Is there anything I am doing wrong? What am I missing?
The solution that worked for me was to put array("Scrollable" => 'static') as a configuration option for the select function.

PDO Can't bind two attributes

I'm trying to bind a search term and a limit value to a PDO execute query, but I get error messages no matter which way I do it
public static function searchUsersByName($searchTerm, $results = null) {
//getDBConnection
if($results == null) {
$results = 5;
}
$searchTerm = '%'.$searchTerm.'%';
$query = $database->prepare("SELECT user_id, user_firstname, user_lastname
FROM users_details
WHERE user_firstname LIKE :searchTerm
OR user_lastname LIKE :searchTerm
LIMIT :results");
$query->bindParam(':searchTerm', $searchTerm, PDO::PARAM_STR);
$query->bindParam(':results', $results, PDO::PARAM_INT);
$query->execute();
$search_results = array();
foreach ($query->fetchAll() as $user) {
$search_results[$user->user_id] = new stdClass();
$search_results[$user->user_id]->user_id = $user->user_id;
$search_results[$user->user_id]->user_firstname = $user->user_firstname;
$search_results[$user->user_id]->user_lastname = $user->user_lastname;
}
return $search_results;
}
This is the error I get from this:
PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 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 "5"
It works fine if I take out the bind for LIMIT and just hardcode 5 into the SQL query, but I want to be able to change it if possible
$query->execute(array(':searchTerm' => '%'.$searchTerm.'%', ':results' => $results));
I've tried doing it this way, but of course PDO automatically puts quotes around the values its inserting via this method, and as far as I know you can't put a PDO::PARAM_INT in while using this method.
What am I doing wrong?
Could it be that $results is not an integer? The error seems like your PHP code is posting a string into the query, which would explain the error.
I am guessing this is the issue because of the following piece of code
if($results == null) {
$results = 5;
}
How is $results set in the first place? Via GET/POST? Then it might have been converted to a string.
I've tried your piece of code myself and casting it to an int fixed it for me.
$query->bindParam(':results', intval($results), PDO::PARAM_INT);

using form variables for mysql query

I'm trying to fetch a result from a mysql table using two form variables namely $sessionID and $semesterID. I used the following code and it seems to have an error in the sql syntax
<?php
...
mysql_select_db($database_connChePortal, $connChePortal);
$query_rsRegcourses =sprintf("SELECT * FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s",$sessionID,$semesterID);
$rsRegcourses = mysql_query($query_rsRegcourses, $connChePortal) or die(mysql_error());
$row_rsRegcourses = mysql_fetch_assoc($rsRegcourses);
$totalRows_rsRegcourses = mysql_num_rows($rsRegcourses);
print_r($query_rsRegcourses); die;
...
?>
I tried running the query and I have the following error report
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 'AND vwr.semesterID=' at line 1
thanks
I think you should surround your variable with single quotes '' please change as follow
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'"
Put the %s in single quotes like this
"SELECT * FROM VW_reg vwr WHERE vwr.sessionID='%s' AND vwr.semesterID='%s'",$sessionID,$semesterID);
To insert a variable into query, you have to properly format it.
Two other answers contains improper formatting - so, you shouldn't follow them.
To make formatting more handy, you have to encapsulate sprintf() into function like this:
function paraQuery()
{
$args = func_get_args();
$query = array_shift($args);
$query = str_replace("%s","'%s'",$query);
foreach ($args as $key => $val)
{
$args[$key] = mysql_real_escape_string($val);
}
$query = vsprintf($query, $args);
$result = mysql_query($query);
if (!$result)
{
throw new Exception(mysql_error()." [$query]");
}
return $result;
}
which would apply proper formatting and also will handle errors
Also note that your way of counting records is extremely inefficient and may cause server to hang. You have to query the only data you need. So, if you need only count - request the count only
so, the code would be
mysql_select_db($database_connChePortal, $connChePortal);
$sql = "SELECT count(*) FROM VW_reg vwr WHERE vwr.sessionID=%s AND vwr.semesterID=%s";
$res = paraQuery($sql,$sessionID,$semesterID);
$row = mysql_fetch_row($res);
print_r($row[0]); die;
it will make your query properly formatted and thus invulnerable to SQL injection
also, it seems that $semesterID is not set which may cause some problem too

Why is this MySQL INSERT not working in CI?

For some reason this SQL statement is not working. Can anyone tell me why? (This is a Codeigniter site, if that matters)
Here is my Model (where my error is pointing me to)
public function edit_profile($ID, $field, $new_info)
{
$sql = "UPDATE users SET ?=? WHERE id=?";
$query = $this->db->query($sql, array($field, $new_info, $ID)); // <<<< LINE 42
return $query;
}
And this is the error I'm getting
Error Number: 1064
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 ''first_name'='oooo' WHERE id='151'' at line 1
UPDATE users SET 'first_name'='oooo' WHERE id='151'
Filename: /Applications/MAMP/htdocs/MY_SITE/models/member_model.php
Line Number: 42
My table is called 'users', and I have a 'first_name' and 'id' column.
Ideas?
EDIT
Just because it seems to come up a bit I want to clarify that the variables I am passing in here have NO QUOTES OR BACKTICKS. They are being added somewhere (and it seems like the ->query method, but I cant imagine that's true? .. dunno though, cause it's my first CI project)
Here is the controller that is passing to the model...
public function profileEdit()
{
$ID = $this->the_user->id;
$field = $this->input->post('edit_field')
$field = strstr($field,'_edit', true);
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if( $this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}
else
{
echo 'error';
}
}
i suggest use like this :
public function edit_profile($ID, $field, $new_info)
{
$sql = "UPDATE users SET $field =? WHERE id=?"; # UPDATED (remove $this->db->escape())
$query = $this->db->query($sql, array($new_info, $ID)); // <<<< LINE 42
return $query;
}
if $field is not secured you can use escape functions .
EDIT :
$this->db->escape() will add quotes around variable so you will get an error again .

SImple Query Error

I'm running a function that checks whether or not an user has already submitted a question. I've narrowed the problem down to my function which runs a query code. For some reason it is not working. The function does work when the part that involved AND user_requester... is not there. I'm sure it's some sort of syntax error but I don't get a response from the error reporting. Here is the code below:
function question_exists ($question, $user_id) {
$question = sanitize($question);
$query = mysql_query("SELECT COUNT(`primary_id`) FROM `requests` WHERE
`question_asked`= '$question' AND `user_requester` = $user_id");
return (mysql_result($query, 0) == 1) ? true : false;
}
Clarification: I want to prevent an user from submitting the same question twice. That is the purpose of adding the AND section to the where clause in the query. When I do add the AND section, everything goes to pieces and the user can submit the same question anyways.
I would try doing all steps separately so you can test the result of each operation individually. Your return line is handling a lot of things and so it's hard to tell where you problem is. Something like this...
function question_exists( $question, $user_id )
{
$question = sanitize( $question );
$user_id = (int) $user_id; // additional sanitization in case you didn't do it already.
$sql = "SELECT COUNT(`primary_id`) FROM `requests` WHERE
`question_asked`= '$question' AND `user_requester` = $user_id";
$result = mysql_query( $sql );
if ( !$result ) {
// Note: this would be better sent to an error handling function, this is just for simplicity's sake.
echo 'Mysql query error: ' . mysql_error();
exit;
}
$row = mysql_fetch_row ( $result );
if ( $row ) {
return true;
} else {
// temporary debug code
echo "unknown error</ br>\n";
echo "sql: " . $sql . "</ br>\n";
echo "<pre>";
var_dump( $row );
echo "</pre>";
exit();
// real code for after problem is solved
return false;
}
}
If this still doesn't help and you haven't already, dump your $question and $user_id vars to make sure that you are receiving them and your sanitize function isn't doing something incorrectly. Note, I have not run this code so there may be syntax errors.
What kind of error reporting are you referring to? A query failing will not trigger any PHP errors/warnings. You'd need somethign like
$query = mysql_query(...) or die(mysql_error());
to see what really happened.
$query = mysql_query("SELECT COUNT(`primary_id`) FROM `requests` WHERE
`question_asked`= '$question' AND `user_requester` = {$user_id}");
Add curly braces to your variable in the query.

Categories