"mysql_fetch_assoc()" error when data in mysql field is changed - php

I have a mySQL database from where I fetch some data via PHP.
This is what I've got:
if ($db_found) {
$URL_ID = $_GET["a"];
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = $URL_ID";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
$firstname = $db_field['firstname'];
$surname = $db_field['surname'];
$function = $db_field['function'];
$email = $db_field['email'];
$telnr = $db_field['telnr'];
}
mysql_close($db_handle);
}
else {
print "Database not found... please try again later.";
mysql_close($db_handle);
}
The URL_ID field in my mySQL database is, for this example, 001. When I go to www.mydomain.com/index.php?a=001 it fetches all the data, puts it into a variable, and I can echo the variables without any problem.
Now, I want to change the URL_ID, and I've changed it to "62ac1175" in the mySQL database. However, when I proceed to www.mydomain.com/index.php?a=62ac1175, I get this error message:
Warning: mysql_fetch_assoc() expects parameter 1 to be resource,
boolean given in
mydomain.com\db_connect.php on line 17
The field in mySQL has varchar(8) as type and utf8_general_ci as collation.
If I change the entry back to 001 and change my URL to ?a=001, it works fine again.
What's going wrong?

You are not doing any error checking in your query, so it's no wonder it breaks if the query fails. How to add proper error checking is outlined in the manual on mysql_query() or in this reference question.
Example:
$result = mysql_query($SQL);
if (!$result)
{ trigger_error("mySQL error: ".mysql_error());
die(); }
your query is breaking because you aren't wrapping the input in quotes. You can avoid* quotes only for integers (which 62ac1175 is not). Try
$SQL = "SELECT * FROM tb_employees WHERE URL_ID = '$URL_ID'";
Also, the code you show is vulnerable to SQL injection. Use the proper sanitation method of your library (like mysql_real_escape_string() for the classic mysql library that you are using), or switch to PDO and prepared statements.
In your code, this would look like so: Instead of
$URL_ID = $_GET["a"];
do
$URL_ID = mysql_real_escape_string($_GET["a"]);
* however, if you avoid quotes, mysql_real_escape_string() won't work and you need to check manually whether the parameter actually is an integer.

Related

Error Query PHP after migrate to mysql database

I have execute query using PHP which previously executed on mssql server database . Now with the same table and data. I using mysql database to execute my query. But error happen. Any suggestion for my query below in order to can execute using mysql database :
$year = mysql_query("SELECT * FROM education_year ORDER BY id DESC");
if (isset($_GET['year'])){
$educationyear= mysql_fetch_array(mysql_query("SELECT * FROM educationyear WHERE year='{$_GET['year']}'"));
}else {$educationyear = mysql_fetch_array($year);}
$kode['KODE'] = mysql_fetch_array(mysql_query("SELECT KODE FROM educationyear WHERE year='$educationyear'"));
$result = mysql_query("SELECT * FROM Province");
while($row = mysql_fetch_array($result))
{
$xd = mysql_fetch_array(mysql_query("SELECT COUNT (*) AS total FROM child WHERE id_province='{$row['province_code']}' AND education='A'
AND educationyear='{$educationyear['KODE']}'"));
}
Error message like below :
Notice: Array to string conversion in C:\xampp\htdocs\xy\demo.php on line 19
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\xy\demo.php on line 20 .
Its line when execute $xd query.
There are a few problems with your code
1st: When you use an array within double-quoted string, do not quote the array key. Change
"...WHERE year='{$_GET['year']}..."
"...WHERE id_province='{$row['province_code']}'..."
To:
"...WHERE year='{$_GET[year]}..."
"...WHERE id_province='{$row[province_code]}'..."
2nd: The design pattern below is not good:
mysql_fetch_array(mysql_query("SELECT...")
You're taking the result of mysql_query and feeding it directly to mysql_fetch_array. This works as long as the query succeeds and returns a resource. If the query fails, it will return FALSE and mysql_fetch_array will trigger the error you see:
mysql_fetch_array() expects parameter 1 to be resource, boolean given
Instead, make sure there is no error before proceeding
$result = mysql_query("SELECT...")
if($result===false){
//Query failed get error from mysql_error($link).
//$link is the result of mysql_connect
}
else{
//now it's safe to fetch results
$record = mysql_fetch_array($result);
}
3rd: do not use mysql_ functions. They have been abandoned for years and have been removed from the most recent version of PHP. Switch to MySQLi or PDO
4th: learn about prepared statements. You're using user supplied input directly in your query ($_GET['year']) and this makes you vulnerable to SQL injection.

PDO Prepared Statement over ODBC Sybase "PARAM datastream" error

I am trying to convert some old PHP ODBC queries over to PDO Prepared statements and am getting an error I cannot find too much information on.
The Error is:
"[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]There is no host variable corresponding to the one specified by the PARAM datastream. This means that this variable '' was not used in the preceding DECLARE CURSOR or SQL command. (SQLExecute[3801] at ext\pdo_odbc\odbc_stmt.c:254)"
I am searching for a single row in the database using a 6 digit ID that is stored in the database as a VARCHAR but is usually a 6 digit number.
The database connection is reporting successful.
The ID passed by the query string is validated.
The prepared statement results in the above error.
The backup straight ODBC_EXEC statement in the else clause returns the data I am looking for.
//PDO Driver Connect to Sybase
try {
$pdo = new PDO("odbc:Driver={Sybase ASE ODBC Driver};NA=server,5000;Uid=username;Pwd=password;");
$pdo_status = "Sybase Connected";
} catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
if((isset($_GET['id'])) AND ($_GET['id'] != "")) {
//Validate ID String
if(!preg_match("/^[A-Za-z0-9]{5,7}/",$_GET['id'])) {
$query1_id = FALSE;
echo "Invalid ID";
exit;
} else {
$query1_id = $_GET['id'];
}
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= ?");
$query1->execute(array($query1_id));
if($query1->errorCode() != 0) {
$person_data = $query1->fetch(PDO::FETCH_ASSOC);
echo "Person Data from PDO: ";
print_r($person_data);
} else {
$errors = $query1->errorInfo();
echo $errors[2];
//Try the old way to confirm data is there.
$odbc_query1 = "SELECT * FROM People WHERE PersonId='$query1_id' ";
$person_result = odbc_exec($conn,$odbc_query1) or die("Error getting Data, Query 1");
$person_data = odbc_fetch_array($person_result);
echo "Person Data from ODBC_EXEC: ";
print_r($person_data);
}
It also fails if I use:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= :id ");
$query1->execute(array(":id"=>$query1_id));
Does anyone have experience with this error?
Edit: Sybase Manual says this about the error...
Error 3801: There is no host variable corresponding to the one specified by the PARAM datastream. This means that this variable `%.*s' was not used in the preceding DECLARE CURSOR or SQL command.
Explanation:
Adaptive Server could not perform the requested action. Check your command for missing or incorrect database objects, variable names, and/or input data.
Which is odd because my error (quoted at the top) doesn't tell me which variable has no host.
Also fails if I use...
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= :id ");
$query1->bindParam(':id',$query1_id,PDO::PARAM_STR); //Or PARAM_INT
$query1->execute();
The query works if I place the variable in the query like this...
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= '$query1_id'");
So I think it has something to do with the parameter not being bound to the placeholder but I can't figure out why.
If I can't work this out I'll have to revert to building my query as a string and hoping my input validation is bullet proof.
Your problem seems to be with the default data type PHP assigns to variables in the placeholders. The SQL Statement is looking for a number but PHP is interpreting it as something else. You can prevent this using quotes around the placeholder variable. Notice that in the statements that work you have apostrophes ('') around the value that PHP sees:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= '$query1_id'");
Try this when using the placeholder it should be the same:
$query1 = $pdo->prepare("SELECT * FROM People WHERE PersonId= ':id'");

PHP mysql_query Syntax Error

<?php
mysql_connect("localhost","root","");
mysql_select_db("hftwmvirtualdb");
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
?>
I am trying to use posted data from an android application to trigger a query and retrieve the results from the mysql database. The Table has 4 columns, and I'm trying to retrieve the value in the third column by defining the values in the first 3 columns. Each time i clicked the button, I get the parsing error to find out my PHP script was not processing the SQL query. When running the scriptthrough the browser I get the messages:
Undefined index: Booknum in C:\wamp\www\GetVerse.php on line 4
Undefined index: Chapternum in C:\wamp\www\GetVerse.php on line 5
Notice: Undefined index: Versenum in C:\wamp\www\GetVerse.php on line 6
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 CHAPTERID = AND VERSENO =' at line 1
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\wamp\www\GetVerse.php on line 9.
I understand i get the warning messages 1-3 is because I did not submit the post data but the latter I don't know how to fix as I have tried using the correct syntax, I tried removing "=" for "like" and that failed also. What is the problem?.
The undefined index errors are, as you specified, occurring because you did not submit the post data. This, in turn, is causing the variables $Booknum, $Chapternum, and $Versenum to be empty.
With the empty variables, the MySQL query is being generated with a WHERE clause like:
WHERE `BOOKID` = AND `CHAPTERID` = AND ...
The missing values are causing invalid MySQL, hence your error. Additionally, as you've specified (in a comment) that the POST-values are strings (and not integers which is what I would have assumed based on their usage and names), you have to wrap the values in quotes in your MySQL query too. If you do not wrap the values in quotes, even valid strings may cause the query to fail.
To fix this, try something like:
$Booknum = isset($_POST['Booknum']) ? mysql_real_escape_string(trim($_POST['Booknum'])) : null;
$Chapternum = isset($_POST['Chapternum']) ? mysql_real_escape_string(trim($_POST['Chapternum'])) : null;
$Versenum = isset($_POST['Versenum']) ? mysql_real_escape_string(trim($_POST['Versenum'])) : null;
if (!empty($Booknum) && !empty($Chapternum) && !empty($Versenum)) {
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = '" . $Booknum . "' AND `CHAPTERID` = '" . $Chapternum . "' AND `VERSENO` = '" . $Versenum . "'");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
mysql_close();
}
This will verify that the values are properly set - if not, they will be set to null. If all three values are not empty, via PHP's empty(), your query will be executed.
This is what your SQL query will look like when the variables are substituted in:
SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = AND `CHAPTERID` = AND `VERSENO` =
When the variables contain no content (as they won't if you submit no data), the query is meaningless: the syntax is malformed.
Check whether the data is posted before doing the query. Moreover, it will also profit you to start using parameterised queries (using MySQLi or PDO) for security and convenience.
The "undefined index" messages you're getting are because those variables are not set. Check that you're actually posting those to the script.
The empty variables are why your query is wrong and you get an error.
Consider using PDO as the "mysql_" commands are deprecated. You should check your inputs before passing them to the query. isset() will work for that.
CHeck whether the Post data is coming or not, undefined index it is because, there is no data for the variables you have used. SO first verify it and then execte the SQL query.
if(isset($_POST['Booknum']) && isset($_POST['Chapternum']) && isset($_POST['Versenum']))
{
$Booknum = mysql_real_escape_string($_POST['Booknum']);
$Chapternum = mysql_real_escape_string($_POST['Chapternum']);
$Versenum = mysql_real_escape_string($_POST['Versenum']);
$sql = mysql_query("SELECT `VERSETEXT` FROM `booktable` WHERE `BOOKID` = $Booknum AND `CHAPTERID` = $Chapternum AND `VERSENO` = $Versenum");
echo mysql_error();
while($row=mysql_fetch_assoc($sql));
print(json_encode($row));
}
else
{
echo "No post data";
}

mysql_num_rows error in PHP with mysql_query

Hi i am too new too php and mysql and i want to count the member number due to the search made by user. However, mysql_num_rows doesnt work.
mysql_num_rows(mysql_query("SELECT * FROM members WHERE $title LIKE '%$_POST[search]%' LIMIT $start,$member_number"));
It says "mysql_num_rows(): supplied argument is not a valid MySQL result resource in ..."
NOTE: $title is a select menu which user choose where to search. LIMIT is, as you know :), number of member which is shown in a page.
And also $start= ($page-1)*$member_number; in order to set the first entry in that page. I think the problem is here but i cant solve it. :(
Your query probably has an error, in which case mysql_query will return false.
For this reason, you should not group commands like this. Do it like this:
$result = mysql_query("...");
if (!$result)
{ echo mysql_error(); die(); } // or some other error handling method
// like, a generic error message on a public site
$count = mysql_num_rows($result);
Also, you have a number of SQL injection vulnerabilities in your code. You need to sanitize the incoming $search variable:
$search = mysql_real_escape_string($_POST["search"]);
... mysql_query(".... WHERE $title LIKE '%$search%'");
if $start and $end come from outside, you also need to sanitize those before using them in your LIMIT clause. You can't use mysql_real_escape_string() here, because they are numeric values. Use intval() to make sure they contain only numbers.
Using a dynamic column name is also difficult from a sanitation point of view: You won't be able to apply mysql_real_escape_string() here, either. You should ideally compare against a list of allowed column names to prevent injection.
you have to use GET method in your form, not POST.
mysql_num_rows doesn't make sense here.
If you're using limit, you already know the number*.
If you want to know number, you shouldn't use limit nor request rows but select number itself.
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members WHERE $title LIKE '%$search%'";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
$row = mysql_fetch_row($res);
$members_found = $row[0]
in case you need just 5 records to show on the page, no need for mysql_num_rows() again:
// Get LIMIT params
$member_number = 5;
$start = 0;
if (isset($_GET['page'])){
$start = abs($_GET['page']-1)*$member_number;
}
// get your $title safe
$fields = array("name","lastname");
$key = array_search($_GET['title'],$fields));
$title = $fields[$key];
//escape your $search
$search = mysql_real_escape_string($_GET['search']);
$sql = "SELECT count(*) FROM members
WHERE `$title` LIKE '%$search%'
LIMIT $start, $member_number";
$res = mysql_query($query) or trigger_error(mysql_error()." in ".$sql);
while($row = mysql_fetch_assoc($res){
$data[] = $row;
}
Now you have selected rows in $data for the further use.
This kind of error generally indicates there is an error in your SQL query -- so it has not been successful, and mysql_query() doesn't return a valid resource ; which, so, cannot be used as a parameter to mysql_num_rows().
You should echo your SQL query, in order to check if it's build OK.
And/or, if mysql_query() returns false, you could use mysql_error() to get the error message : it'll help you debug your query ;-)
Typically, your code would look a bit like this :
$query = "select ..."; // note : don't forget about escaping your data
$result = mysql_query($query);
if (!$result) {
trigger_error(mysql_error()." in ".$query);
} else {
// use the resultset
}

PHP mySql update works fine on localhost but not when live

I have a a php page which updates a mySql database it works fine on my mac (localhost using mamp)
I made a check if its the connection but it appears to be that there is a connection
<?php require_once('connection.php'); ?>
<?php
$id = $_GET['id'];
$collumn = $_GET['collumn'];
$val = $_GET['val'];
// checking if there is a connection
if(!$connection){
echo "connectioned failed";
}
?>
<?php
$sqlUpdate = 'UPDATE plProducts.allPens SET '. "{$collumn}".' = '."'{$val}'".' WHERE allPens.prodId = '."'{$id}'".' LIMIT 1';
mysql_query($sqlUpdate);
// testing for errors
if ($sqlUpdate === false) {
// Checked this and echos NO errors.
echo "Query failed: " . mysql_error();
}
if (mysql_affected_rows() == 1) {
echo "updated";
} else {
echo "failed";
}?>
In the URL i pass in parameters and it looks like this: http://pathToSite.com/updateDB.php?id=17&collumn=prodid&val=4
Maybe this has to do with the hosting? isn' t this simple PHP mySql database updating? what can be wrong here?
Why on localhost it does work?
Why on live server it doesn't?
Let's start with troubleshooting your exact problem. Your query is failing for some reason. We can find out what that problem is by checking what comes back from mysql_query, and if it's boolean false, asking mysql_error what went wrong:
$sh = mysql_query($sqlUpdate);
if($sh === false) {
echo "Query failed: " . mysql_error();
exit;
}
You have other problems here. The largest is that your code suffers from an SQL Injection vulnerability. Let's say your script is called foo.php. If I request:
foo.php?collumn=prodId = NULL --
then your SQL will come out looking like:
UPDATE plProducts.allPens SET prodId = NULL -- = "" WHERE allPens.prodId = "" LIMIT 1
-- is an SQL comment.
I just managed to nuke all of the product IDs in your table.
The most effective way to stop SQL injection is to use prepared statements and placeholders. The "mysql" extension in PHP doesn't support them, so you'd also need to switch to either the must better mysqli extension, or the PDO extension.
Let's use a PDO prepared statement to make your query safe.
// Placeholders only work for *data*. We'll need to validate
// the column name another way. A list of columns that can be
// updated is very safe.
$safe_columns = array('a', 'b', 'c', 'd');
if(!in_array($collumn, $safe_columns))
die "Invalid column";
// Those question marks are the placeholders.
$sqlUpdate = "UPDATE plProducts.allPens SET $column = ? WHERE allPens.prodId = ? LIMIT 1";
$sh = $db->prepare($sqlUpdate);
// The entries in the array you pass to execute() are substituted
// into the query, replacing the placeholders.
$success = $sh->execute(array( $val, $id ));
// If PDO is configured to use warnings instead of exceptions, this will work.
// Otherwise, you'll need to worry about handling the exception...
if(!$success)
die "Oh no, it failed! MySQL says: " . join(' ', $db->errorInfo());
Most mysql functions return FALSE if they encounter an error. You should check for error conditions and if one occurs, output the error message. That will give you a better idea of where the problem occurred and what the nature of the problem is.
It's amazing how many programmers never check for error states, despite many examples in the PHP docs.
$link = mysql_connect(...);
if ($link === false) {
die(mysql_error());
}
$selected = mysql_select_db(...);
if ($selected === false) {
die(mysql_error());
}
$result = mysql_query(...);
if ($result === false) {
die(mysql_error());
}
Your call to mysql_query() is faulty; you're checking the contents of the variable you're passing in but the function call doesn't work that way. It returns a value which is what you should check. If the query failed, it returned false. If it returns data (like from a SELECT) it returns a resource handle. If it succeeds but doesn't return data (like from an INSERT) it returns true.
You also have some problems constructing your SQL. #Charles mentions SQL injection and suggests prepared statements. If you still want to construct a query string, then you need to use mysql_real_escape_string(). (But I would recommend you read up on the mysqli extension and use those functions instead.)
Secondly, you're concatenating strings with embedded substitution. This is silly. Do it this way instead:
$sqlUpdate = 'UPDATE plProducts.allPens SET '.$collumn.' = \''.$val.'\'
WHERE allPens.prodId = '.intval($id).' LIMIT 1';
If you must accept it in the querystring, you should also check that $collumn is set to a valid value before you use it. And emit and error page if it's not. Likewise, check that $id will turn into a number (use is_numeric()). All this is called defensive programming.

Categories