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'";
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
when i go to produkdelete.php i can view the record that i want to delete, but when i confirm to delete there is no deleted record
this is my script :
$key = #$_GET["key"];
case "I": // Get a record to display
$tkey = $key;
$strsql = "SELECT * FROM `produk` WHERE `id`=".$tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
if (mysql_num_rows($rs) == 0)
{
ob_end_clean();
header("Location: "."produklist.php");
}
$row = mysql_fetch_assoc($rs);
$x_id = $row["id"];
$x_kdprod = $row["kdprod"];
$x_namaprod = $row["namaprod"];
$x_diskripsi = $row["diskripsi"];
$x_harga = $row["harga"];
mysql_free_result($rs);
break;
case "D": // Delete
// Open record
$tkey = $key;
$strsql = "DELETE FROM `produk` WHERE `id`=".$tkey;
$rs = mysql_query($strsql, $conn) or die(mysql_error());
mysql_free_result($rs);
mysql_close($conn);
ob_end_clean();
header("Location: produklist.php");
break;
the key variable is send from "produkdelete.php?key=".urlencode($row["id"]);
and everytime i run this the output just come like this :
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 '=' at line 1
In SQL Management Studio this won't run.
$strsql = "DELETE FROMprodukWHEREid=".$tkey;
Lose the ` and it should execute.
With PDO for added security (explanation below)
$myServer = "put url to your server here";
$myDB = "put name of database here";
$name = "login name db";
$pw= "password db";
try
{
$dbConn = new PDO("mysql:host=$myServer;dbname=$myDB", $name, $pw);
}
catch( PDOException $Exception )
{
//Uncomment code to show error
//var_dump($Exception);
}
function doPDOQuery($sql, queryArguments = array())
{
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArguments );
}
$sql = 'SELECT * FROM produk WHERE id= :id';
doPDOQuery( $sql, array(":id" -> $tkey) );
This should execute on your server. It's using the PDO module for creating prepared queries. That means that the query itself is created by the database-driver itself. This prevents SQL-injection. This is a reason why MySQL_functions are deprecated.
For delete, update and insert the code above is sufficient. You need to do a $sth->fetchAll() to retrieve rows from a select.
Why are PHP's mysql_ functions deprecated?
so I am new in StackOverflow :), I have a problem to answer a question in php5,
This is the question :
Create a PHP 5.4 script to check availability of many Sites (via Echo Protocol):
* Get the list of sites (domains) from MySQL database.
so I write this script and I want if it's the good answer :
<?php
$dbname = 'mysql_dbname';
if (!mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
$sql = "SHOW TABLES FROM $dbname";
$result = mysql_query($sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "Table: {$row[0]}\n";
}
mysql_free_result($result);
?>
try something like this
$con = mysqli_connect(‘hostname’, ‘username’, ‘password’, ‘database’);
$result = mysqli_query($con , "select column_name from table_name");
while($data = mysqli_fetch_array($result))
{
echo $data['column_name'];
}
this will tell you the databases that have rights to be connected to
mysql_connect('localhost') or die ("Connect error");
$res = mysql_query("SHOW DATABASES");
while ($row = mysql_fetch_row($res)) {
echo $row[0], '<br/>';
}
You need to select a database before you use mysql_query.
$connection = mysql_connect('mysql_host', 'mysql_user', 'mysql_password');
//Write code to Check the connection
mysql_select_db('database_name', $connection);
//Write code to query
But as Robin mentioned in the comment, mysql* apis are deprecated. Use Mysqli or Pdo_Mysql. details here: http://in3.php.net/mysql_select_db
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);
}
}
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.