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.
Related
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
what is wrong with this script? it keeps giving my erros but will not tell me what is wrong
I need this to lookup channel number from the item number passed in url. then echo the channel number
<?php
$id = $_GET['item'];
if (!$link = mysql_connect('server', 'user', 'pass')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('xmlrpc', $link)) {
echo 'Could not select database';
exit;
}
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['channel'];
}
mysql_free_result($result);
?>
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'") or die(mysql_error());
To
$sql = "SELECT channel FROM channels WHERE item = '".$_GET['item']."'";
As a sidenote do not use mysql_ functions, they became obsolete (PHP 5.5). Use PDO instead for example, as it stands your code is vulnerable to SQL injections.
when item is already declared as a variable $id
$id = $_GET['item'];
you could already use it as a variable in your mysql
$sql = mysql_query("SELECT channel FROM channels WHERE item = '".$_GET['item']."'")or die(mysql_error());
change it into
$sql="SELECT * FROM channels WHERE item ='$id'";
I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.
This is my source where I have this problem:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
What is wrong?
Thanks in advance!
You are mixing mysql and mysqli.
Try something like:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);
change to
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).
You don't even need the second $con parameter really.
Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.
I'd var_dump($con) before the mysql query to make sure it's a valid connection.
I got a simple query looking like this:
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
Running this query gives me absolutely nothing. No errors but no result at the same time. I can't figure out whats wrong, help me please.
It looks like there may be a few things going on here:
According to the mysqli_connect_errno() Documentation, you should be checking for !$con rather than mysqli_connect_errno($con) in your if statement.
When a connection error is encountered, you're calling the error function but not printing it.
According to the mysqli_query() documentation, the first argument should be the database connection, the second being the query itself.
When a query errors out, you're calling mysql_error() when you should be calling mysqli_error(), passing it the connection. Again, according to documentation
Try this out and see if this resolves your problems:
<?php
$con = mysqli_connect("host","username","password","default_database");
if(!$con) {
print mysqli_connect_error();
} else {
$query = "SELECT * FROM `users_t`";
$result = mysqli_query($con, $query) or die (mysqli_error($con));
while($row = mysqli_fetch_assoc($result)) {
echo $row['email'];
}
}
$result = mysqli_query($query) or die (mysql_error());
Needs a mysqli resource link and also its not mysql_error()
if ($result = mysqli_query($con,$query))
{
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
}
}
PHP is case-sensitive, so there is a very good change that your column in the database is actually named Email and then you have no result when you check $row['email'], because the E has to be upper case.
What you can do is make sure you use the right case in PHP, or select just the fields you want. MYSQL isn't case-senstive, so if you do the following it will work.
Also a good way to check if you have the right case: use var_dump($row) (I've added it to the code just to show you)
$con = mysqli_connect("host","username","password","default_database");
if(mysqli_connect_errno($con))
{
mysqli_connect_error();
}
else
{
$query = "SELECT email FROM `users_t`";
$result = mysqli_query($query) or die (mysql_error());
while($row = mysqli_fetch_assoc($result))
{
echo $row['email'];
var_dump($row);
}
}
I am trying to insert data in table in mysql database through php code but I am always getting following error:
Invalid query: Table 'whatsup_wp1.pushDevices' doesn't exist
I am using following code:
<?php
$deviceid = $_GET["deviceid"];
$link = mysql_connect('localhost', 'whatsup_wp1', 'XSvUCl0FugzV4');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('whatsup_wp1', $link);
if (!$db_selected) {
echo 'Can\'t use whatsup_wp1 : ' . mysql_error();
}
else
{
//echo 'connect';
}
//$query = "select count(*) from city";
//$query = "insert into devices (pushID) values('".$deviceid."')";
$query = "INSERT INTO pushDevices(device) VALUES ('".$deviceid."')";
echo $query;
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
echo $result;
?>
This database have more tables and I am able to use them. I am having problem with the tables that I am creating today. They appears in phpmyadmin but somehow I am not able to get use them through my php code.
Any help may be vital for me. I have spent complete day on it.
Thanks
Pankaj
Its hard to tell by What your saying but i have a suggestion.... It looks like theres no table selected try this
it formatted like this
$query = "INSERT INTO mydb.mytable
(mytablefield)
VALUES
('myfieldvalue')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
My guess is you meant for it to be like this?
$query = "INSERT INTO whatsup_wp1.devices
(device)
VALUES
('".$deviceid."')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
And for security reasons i recommend this...
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Change to
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Personally i just use it like this
$result = mysql_query("INSERT INTO mytable
(mytablefield)
VALUES
('myfieldvalue')");
if($result){echo "Works!";}
else{die('Invalid query: ' . mysql_error());exit();}
If you are on Linux, check that the case is the same.
On windows MySql is case insensitive, on Linux, it is case sensitive.
Also, you are missing a space after pushDevice: pushDevice(...