Having Trouble Performing a Simple MySql Query - php

I'm very new to PHP and still learning the basics and I'm stuck on an issue I'm hoping someone could help me with.
I have the following code;
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
if($MfgQueryRun = mysql_query($MfgQuery)) {
if (mysql_num_rows($MfgQueryRun)==NULL){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
} else {
echo 'Query Unsuccessful';
}
But for a reason unknown to me I keep getting 'No Mfg Results Returned' but if I copy and paste the query by itself into the MySQL box in PHPMyAdmin it returns a result properly.
What gives??
BTW, Here's exactly what I can insert into PHP MyAdmin's SQL box;
SELECT `Mfg` FROM `categories` WHERE `ID` = 10
and this returns a result but using the code above, it does not.
If anyone wouldn't mind showing me where I went wrong I'd be most appreciative and I thank you in advance

try this
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
$MfgQueryRun = mysql_query($MfgQuery) ;
$row = mysql_fetch_array($MfgQueryRun) ;
if (mysql_num_rows($MfgQueryRun)== 0 ){
echo 'No Mfg Results Returned';
} else {
$Mfg = $row['Mfg'];
echo $Mfg;
}

Try
$MfgQuery = "SELECT `Mfg` FROM `categories` WHERE `ID` = 10";
$MfgQueryRun = mysql_query($MfgQuery);
if($MfgQueryRun) {
if (mysql_num_rows($MfgQueryRun) == 0){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
} else {
echo 'Query Unsuccessful';
}

if (mysql_num_rows($MfgQueryRun)){
echo 'No Mfg Results Returned';
} else {
$Mfg = $MfgQueryRun['Mfg'];
echo $Mfg;
}
Try this remove the NULL in comparison. because mysql_num_rows returns numeric values.

First, you should not use mysql_* functions, they are deprecated (outdated) as of PHP 5.5.0, and will be removed in the future. Use mysqli instead.
Second, you're not testing properly. PHP has no strong types, so a test '== null' does not always do, what you'll expect. See the PHP manual for comparision operators. To test against null, always use is_null().
Third, you're not fetching the data.
Using MySQLi, the code would look similar to this:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno != 0) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
die(); // or return, if in method or function context
}
$result = $mysqli->query("SELECT `Mfg` FROM `categories` WHERE `ID` = 10");
if ($result === false) {
echo "Query failed: (" . $mysqli->errno . ") " . $mysqli->error;
die(); // or return, if in method or function context
}
printf("Select returned %d rows.\n", $result->num_rows);
$row = $result->fetch_assoc();
echo $row['Msg'];
/* free result set */
$result->close();

Related

How to check if MySQL results returned empty in PHP?

How to check MySQL results are empty or not. If MySQL query results are empty then else condition should not be executed.
In case MySQL results in data there & in else condition my error my message is there but it is not showing any error message.
I have tried the following code but not showing any alert or echo message on the screen.
<?php
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
if (!empty($res)) {
while ($row = mysql_fetch_row($res)) {
// here my data
}
} else {
echo "no results found";
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"] . " - Name: " . $row["firstname"] . " " . $row["lastname"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Check number of rows
$result = mysqli_query($conn, $sql);
$rowcount=mysqli_num_rows($result);
if($rowcount > 0){
echo "Number of rows = " . $rowcount;
}
else
{
echo "no record found";
}
You can use mysql_num_rows to get count of number of rows returned from query.
if(mysqli_num_rows($res) > 0)
{
// rest of your stuff
}
else
{
echo "No records found.";
}
Note: mysql is deprecated instead use mysqli or PDO as seen above
Security Tip First of all stop using the mysql_* functions because they are not secure for production and later versions has stopped support for this API. So if accidentally you used those function in production then you can be in trouble.
It is not recommended to use the old mysql extension for new development, as it was deprecated in PHP 5.5.0 and was removed in PHP 7. A detailed feature comparison matrix is provided below. More Read
For your answer you have to only check no of rows is zero or not
Read this Post at php documentation with Example.
mysqli_num_rows
mysql_* API has been removed from PHP long time ago. To access the database you should use PDO. Checking if PDO has returned any results is actually pretty simple. Just fetch the results and if the array is empty then there was nothing returned from MySQL.
$stmt = $pdo->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->execute([$_SESSION['amount1'], $_SESSION['amount2']]);
$records = $stmt->fetchAll();
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
There is also mysqli library and if you are stuck using it you have to do a little more work, but the idea is the same. Fetch all results and if nothing was fetched then it means MySQL returned no rows.
$stmt = $mysqli->prepare('SELECT * FROM hall_search_data_1 WHERE rent BETWEEN ? AND ?');
$stmt->bind_param('ss', $_SESSION['amount1'], $_SESSION['amount2']);
$stmt->execute();
$records = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if ($records) {
foreach ($records as $row) {
// your logic
}
} else {
echo 'No records found!';
}
You can use mysql_num_rows(); to check your query return rows or not
$sql = "select * from hall_search_data_1 where rent BETWEEN '".$_SESSION['amount1']."' AND '".$_SESSION['amount2']."'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows>0)
{
echo "data return from query";
}else{
echo "data not return";
}
Note:- mysql is deprecated instead use mysqli or PDO

How to prevent SQL-injection when using MySQLi

I'm building a simple form and want to secure this against the following SQL-injections:
- blind-injection
- boolean-based
- blind injection
- UNION query-based
- Stacked queries
- error-based injections
I thought that I had it all secured, but when I run SQL-map it still exploits my database.
<?php
$input = $_GET['input'];
if ($input) {
$db = mysqli_connect("localhost", "sec", "dubbelgeheim", "bookshop");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$escaper = real_escape_string($input);
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $escaper);
$statement->execute();
$result = $statement->get_result();
$statement->close();
$count = $result->num_rows;
if ($count > 0) {
while ($row = $result->fetch_assoc()) {
echo "Product:" . $row['ProductId'] . "<br>";
echo "Annotation:" . $row['Comment'] . "<br>";
echo "TestOK!<br>";
}
}
else {
echo 'No record!';
}
$result->free();
$db->close();
}
?>
Did I forget something?
Can anyone help?
Thanks in advance!
Your problem is caused by you displaying mysqli_connect_error(). This is OK for testing but should NOT be used in production code. You also don't need $escaper = real_escape_string($input);.
Try this instead
/* check connection */
if (mysqli_connect_errno()) {
file_put_contents('MySQLiErrors.txt',date('[Y-m-d H:i:s]'). mysqli_connect_error()."\r\n", FILE_APPEND);
exit();
}else{
$statement = $db->prepare("SELECT * FROM productcomment WHERE ProductId = ? LIMIT 1");
$statement->bind_param("s", $input);
}

Warning: db2_fetch_assoc(): Fetch Failure

This is probably very simple (I'm a novice), but I haven't been able to find an answer.
I'm using Linux, DB2 and PHP.
My simple DB2 query from PHP only returns rows with integer values, but fails with "Fetch Failure" for anything else (varchar ...).
The query works with db2cli for all values:
echo "select COLUMN from TEST.TABLE"" | ./db2cli execsql -dsn SCHEMA
But fails in PHP:
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$passwd;";
$conn = db2_pconnect($conn_string, '', '');
if ($conn) {
$sql = 'select COLUMN from TEST.TABLE';
$options = array('cursor' => DB2_SCROLLABLE, 'binmode' => DB2_BINARY);
$stmt = db2_prepare($conn, $sql, $options);
if ($stmt) {
$result = db2_execute($stmt);
if (!$result) {
echo "exec errormsg: " .db2_stmt_errormsg($stmt);
}
$total_rows = db2_num_rows($stmt);
print "<br>Total rows: $total_rows";
for ($i = 0; $i < $total_rows; $i++) {
$row = db2_fetch_array($stmt);
print "<br>$row[0]";
}
} else {
echo "exec erromsg: " . db2_stmt_erromsg($stmt);
}
db2_close($conn);
} else {
echo "failed #2 ".db2_conn_errormsg();
}
}
It will display any rows with integer values, but empty strings for everything else with the error "Fetch Failure" in the log. I tried db2_fetch_array, db2_fetch_assoc and db2_fetch_both.
Note: I've added the superfluous stuff like db2_scrollable and db2_num_rows later on in attempts to solve the problem. Unsuccessfully.
EDIT: I can even FILTER by the values that won't display ( SELECT column WHERE column = 'value') and it'll return the correct number of rows.

Checking if data is in a table row

This is my first post so please bear with me with inputting the code into here. Im trying to output some images to a PDF and need to create a if statement that looks for data with in a row.
$connection = mysql_connect("localhost", "testdb", "********")
or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result)) {
$image = $row[1];
$text = $row[2];
}
That's what I have so far and basically I need something along the line of this:
If (data in row 1) {
print $image;
} else {
print $text;
}
It's hard to say exactly what you're looking for since it isn't very clear, but I think what you're wanting to do is check to see if $image has a value, and if so, display it. If not, display $text instead.
If this is the case use empty(). It will tell you if a variable is empty or not.
if (!empty($image))
{
print $image;
}
else
{
print $text;
}
The following things are considered to be empty:
"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
$var; (a variable declared, but without a value)
looks like you just need to test for data in $image
if(!empty($image))
{
echo $image;
}
else
{
echo $text;
}
if( !empty($row[1]) ) {
...
Use isset to check variable.
Like
if(isset($images) !='')
{
echo $images;
}
Although you are using old mysql_* functions which are depreciated, you are almost there
$connection = mysql_connect("localhost", "testdb", "********") or die ("Unable to connect!");
// select database
mysql_select_db("testdb") or die ("Unable to select database!");
// Select all the rows in the test table
$query = "SELECT * FROM test2 WHERE testid=89";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while ($row= mysql_fetch_array($result))
// This will only be called if there is a matching result.
{
echo $row[1];
echo $row[2];
}
Edit: Here is a cut and paste of a section of a query that happen to be open in eclipse:
$arrKPIData = Array();
try{
$dbh = new PDO($this->mySQLAccessData->hostname, $this->mySQLAccessData->username, $this->mySQLAccessData->password);
$stmt = $dbh->query($sql);
$obj = $stmt->setFetchMode(PDO::FETCH_INTO, new kpiData);
$dataCount=0;
foreach($stmt as $kpiData)
{
$arrKPIData[$dataCount]['year']=$kpiData->year;
$arrKPIData[$dataCount]['month']=$kpiData->month;
$arrKPIData[$dataCount]['measure']=$kpiData->kpiMeasure;
$arrKPIData[$dataCount]['var1']=$kpiData->var1;
$arrKPIData[$dataCount]['var2']=$kpiData->var2;
$dataCount++;
unset($stmt);
}
unset($dbh);
}
catch(PDOException $e){
echo 'Error : '.$e->getMessage();
exit();
}
unset($arrKPIData);
I am populating a simple array with data before I cleanse it and convert it into a class further in the code.

Pass a PHP variable to a MySQL query

What is wrong with this code? I get an empty array. I am passing a PHP variable to the query, but it doesn’t work; when I give a hardcoded value the query returns a result.
echo $sub1 = $examSubject[$i];
$subType = $examType[$i];
$query = $this->db->query("select dSubject_id from tbl_subject_details where dSubjectCode='$sub1'");
print_r($query->result_array());
Look up “SQL injection”.
I’m not familiar with $this->db->query; what database driver are you using? The syntax for escaping variables varies from driver to driver.
Here is a PDO example:
$preqry = "INSERT INTO mytable (id,name) VALUES (23,?)";
$stmt = $pdo->prepare($preqry);
$stmt->bindparam(1,$name);
$stmt->execute();
failing to see what you database abstraction layer ($this->db) does, here's the adjusted code from example1 from the mysql_fetch_assoc documentation
<?php
// replace as you see fit
$sub1 = 'CS1';
// replace localhost, mysql_user & mysql_password with the proper details
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = 'SELECT `dSubject_id` ';
$sql .= 'FROM `tbl_subject_details` ';
$sql .= "WHERE `dSubjectCode` ='$sub1';";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['dSubject_id'];
}
mysql_free_result($result);
?>
Let me know what the output is, I'm guessing it will say: 6
Is it CodeIgniter framework you're using (from the $this->db->query statement). If so, why don't you try:
$this->db->where('dSubjectCode',$sub1);
$query = $this->db->get('tbl_subject_details');
If this doesn't work, you've got an error earlier in the code and $sub1 isn't what you expect it to be.

Categories