PHP Resource ID error - php

I want to retrieve or output data in the database but I kept on getting the error called "Resource ID".
Here is my code:
<?php
$host="localhost";
$username="root";
$password ="123192";
$db_name = "customers";
//Connecting to your Host
mysql_connect("$host","$username","$password") or die("Failed To Connect The server");
//Selecting your Database
mysql_select_db("$db_name") or die("Failed To Select The DB");
$name = $_REQUEST['customerName'];
echo 'WELCOME! <b>'.$name.'</b> We hope that you\'ll Enjoy your stay ';
$sql="SELECT Name FROM `people` WHERE id =2 && Name = 'Kyel'";
$rs=mysql_query($sql);
echo "$rs";
?>
If I need improvement regarding my code kindly tell me.

mysql_query() returns a resource. The to string (implicitly triggered by using echo to output it) of that is Resource ID # followed by the id.
A resource in PHP is only supposed to be used with other PHP functions. This includes but is not limited to file, curl, ftp handles, etc.
I could tell you to..
(a) use mysql_fetch_array() (or similar) or
(b) use PDO.
The latter is by far much better advice.

Try this instead of the echo statement:
$array = mysql_fetch_assoc($rs);
var_dump ($array);

Related

delete image from path and database

I am getting the following errors:
Warning: unlink() [function.unlink]: Invalid argument in
C:\xampp\htdocs\SH\owner\delete_img.php
on line 11
and
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
'* FROM img_homestay WHERE imgid='"73"'' at line 1
This is my code for delete image. My images have own imgid. I want to delete it using their imgid.
<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($img['location']);
$result=mysql_query("DELETE * FROM img_homestay WHERE imgid='$imgid'")
or die(mysql_error());
header("Location: editimage1.php");
?>
This is the link of one of the pictures I want to delete:
/SH/owner../data/img1.jpg
From the comment. It's been edited.
Your query should be DELETE FROM. Remove the * from your query.
The full query: DELETE FROM img_homestay WHERE imgid='$imgid'
Also, you can either remove the $result = part from your query, or do this.
if($result) {
//Successfully deleted image.
}
Also, your code is highly susceptible to SQL injection. You are passing in raw user input into your SQL query. At the very least, you should be escaping out quotations, but it is highly recommended that you also use the MYSQLI or PDO set of functions for database connections and queries.
You may also need to need check your permissions for the folder that you are trying to remove the file from. Ideally, folders which house images should be set to chmod 755.
http://mattbango.com/notebook/code/prepared-statements-in-php-and-mysqli/
This link is a very basic introduction to prepared statements, and also provides links for further reading.
EDIT: Full snippet.
<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
$imgid = mysql_real_escape_string($imgid);
$path= $_SERVER['DOCUMENT_ROOT'].'/owner../data/';
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($path.$img['location']);
$result=mysql_query("DELETE FROM img_homestay WHERE imgid='$imgid'") or die(mysql_error());
//Check to see if the query can run
if($result) {
header("Location: editimage1.php");
} else {
//Query failed. Display an error message here.
}
?>
<?php
// This is a sample code in case you wish to check the username from a mysql db table
$link=mysql_connect("localhost", "root","")or die("could not connect");
$db=mysql_select_db("sh",$link) or die ("could not select database");
$imgid = $_GET['imgid'];
$path= $_SERVER['DOCUMENT_ROOT'].'/owner../data/';
// sending query
$select=mysql_query("SELECT location FROM img_homestay WHERE imgid='$imgid'");
$img=mysql_fetch_array($select);
unlink($path.$img['location']);
$result=mysql_query("DELETE FROM img_homestay WHERE imgid='$imgid'") or die(mysql_error());
header("Location: editimage1.php");
?>
This type of error basically needs debugging.
First check whether problem is related to unlink() function or in Sql connectivety.
Create another php file n check whether its working for static path
<?php
$path='/SH/owner../data/img1.jpg'; // update it as per your filepath..path should be from root
if(unlink($path))
{
echo "Deleted file ";
}
else
{
echo "Not Able to Delete File";
}
?>
Lets see what it retruns.
As Part Written by 9997 regarding database connection and query execution seems perfectly fine.

Outputting contents of database mysqli

Hi I know this is a little general but its something I cant seem to work out by reading online.
Im trying to connnect to a database using php / mysqli using a wamp server and a database which is local host on php admin.
No matter what I try i keep getting the error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given when i try to output the contents of the database.
the code im using is:
if (isset($_POST["submit"]))
{
$con = mysqli_connect("localhost");
if ($con == true)
{
echo "Database connection established";
}
else
{
die("Unable to connect to database");
}
$result = mysqli_query($con,"SELECT *");
while($row = mysqli_fetch_array($result))
{
echo $row['login'];
}
}
I will be good if you have a look at the standard mysqli_connect here
I will dont seem to see where you have selected any data base before attempting to dump it contents.
<?php
//set up basic connection :
$con = mysqli_connect("host","user","passw","db") or die("Error " . mysqli_error($con));
?>
Following this basic standard will also help you know where prob is.
you have to select from table . or mysqli dont know what table are you selecting from.
change this
$result = mysqli_query($con,"SELECT *");
to
$result = mysqli_query($con,"SELECT * FROM table_name ");
table_name is the name of your table
and your connection is tottally wrong.
use this
$con = mysqli_connect("hostname","username","password","database_name");
you have to learn here how to connect and use mysqli

PHP unlink() not working to delete files

I am have been trying to setup this code to delete a row on the mysql database as well as the photo that was uploaded with it. It is working GREAT to remove the row data, but it will not get rid of the photo, and I cannot figure out what I am doing wrong. To simplify things, im using the variable $id which is the number of the row entered in the form which triggers this php file:
<?php
$host="localhost"; // Host name
$username="blahblah_plans"; // Mysql username
$password="password"; // Mysql password
$db_name="blahtbl_name"; // Database name
$tbl_name="plans"; // Table name
// Connect to server and select databse.
$conn = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// get value of id that sent from address bar
$id=$_GET['idnum'];
$compositesql="SELECT composite FROM plans WHERE ID ='$id'";
$compositeresult = mysql_query($compositesql) or die(mysql_error());
$compositefilename = "/composite/" + $compositeresult;
$unlink = unlink($compositefilename);
if($unlink) {
echo 'Successfully deleted file: ';
echo $compositefilename;
} else {
echo 'Error deleting file: ';
echo $compositefilename;
}
// Delete data in mysql from row that has this id
$sql="DELETE FROM $tbl_name WHERE ID ='$id'";
$result = mysql_query($sql);
if($result){
header("location:planentry.php");
}
else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
Make sure the path is right, $compositefilename = "/composite/" + $compositeresult; should be the path in the server, it most likely to be
$compositefilename = PATH_TO_YOUR_WEB_ROOT . "/composite/" . $compositeresult;
And php does not use + to concat strings.
The problem is that $compositeresult contains a resource rather than a result set. This line is what's causing it:
$compositeresult = mysql_query($compositesql) or die(mysql_error());
To fix that, store the resource on a variable, then store the result set on another variable, like this:
$compositequery = mysql_query($compositesql) or die(mysql_error());
$compositeresult = mysql_fetch_array($compositequery) or die(mysql_error());
Also, I highly recommend that you start using mysqli or PDO instead of mysql, since it's safer. Also, as xdazz said, PHP's concatenation operator is the dot, not the plus sign. So your $compositefilename should be declared as (note that $compositeresult is an array of data and therefore should have its correct key explicitly written):
$compositefilename = "/composite/" . $compositeresult['composite'];

PHP SQL Truncate

I'm having a problem trying to truncate the 'requestID' field from my requests table.
This is my code.
<?php
include 'mysql_connect.php';
USE fypmysqldb;
TRUNCATE TABLE requestID;
echo "Request ID table has been truncated";
?>
I'm using server side scripting so no idea what error is coming back.
Anyone got an idea?
You aren't executing queries, you're just putting SQL code inside PHP which is invalid. This assumes you are using the mysql_*() api (which I kind of suspect after viewing one of your earlier questions), but can be adjusted if you are using MySQLi or PDO.
// Assuming a successful connection was made in this inclusion:
include 'mysql_connect.php';
// Select the database
mysql_select_db('fypmysqldb');
// Execute the query.
$result = mysql_query('TRUNCATE TABLE requestID');
if ($result) {
echo "Request ID table has been truncated";
}
else echo "Something went wrong: " . mysql_error();
Take a look at the function mysql_query which performs the query execution. The code to execute a query should look something like this.
$link = mysql_connect('host', 'username', 'password') or die(mysql_error());
mysql_select_db("fypmysqldb", $link) or die(mysql_error());
mysql_query("TRUNCATE TABLE requestID", $link) or die(mysql_error());
mysql_close($link);

PHP will not delete from MySQL

For some reason, JavaScript/PHP wont delete my data from MySQL! Here is the rundown of the problem.
I have an array that displays all my MySQL entries in a nice format, with a button to delete the entry for each one individually. It looks like this:
<?php
include("login.php");
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("<br/><h1>Unable to connect to MySQL, please contact support at support#michalkopanski.com</h1>");
//select a database to work with
$selected = mysql_select_db($dbname, $dbhandle)
or die("Could not select database.");
//execute the SQL query and return records
if (!$result = mysql_query("SELECT `id`, `url` FROM `videos`"))
echo 'mysql error: '.mysql_error();
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
?>
<div class="video"><a class="<?php echo $row{'id'}; ?>" href="http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?>">http://www.youtube.com/watch?v=<?php echo $row{'url'}; ?></a><a class="del" href="javascript:confirmation(<? echo $row['id']; ?>)">delete</a></div>
<?php }
//close the connection
mysql_close($dbhandle);
?>
The delete button has an href of javascript:confirmation(<? echo $row['id']; ?>) , so once you click on delete, it runs this:
<script type="text/javascript">
<!--
function confirmation(ID) {
var answer = confirm("Are you sure you want to delete this video?")
if (answer){
alert("Entry Deleted")
window.location = "delete.php?id="+ID;
}
else{
alert("No action taken")
}
}
//-->
</script>
The JavaScript should theoretically pass the 'ID' onto the page delete.php. That page looks like this (and I think this is where the problem is):
<?php
include ("login.php");
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
echo ("Video has been deleted.");
?>
If there's anyone out there that may know the answer to this, I would greatly appreciate it. I am also opened to suggestions (for those who aren't sure).
Thanks!
In your delete.php script, you are using this line :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
The $id variable doesn't exists : you must initialize it from the $_GET variable, like this :
$id = $_GET['id'];
(This is because your page is called using an HTTP GET request -- ie, parameters are passed in the URL)
Also, your query feels quite strange : what about this instead :
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = '$id' ");
ie, removing the '.' : you are inside a string already, so there is nothing to concatenate (the dot operator in PHP is for concatenation of strings)
Note :
if this works on some server, it is probably because of register_globals
For more informations, see Using Register Globals
But note that this "feature" has been deprecated, and should definitely not be used !
It causes security risks
And should disappear in PHP 6 -- that'll be a nice change, even if it breaks a couple of old applications
your code has a big SQL injection hole : you should sanitize/filter/escape the $id before using it in a query !
If you video.id is a string, this means using mysql_real_escape_string
If you where using the mysqli or PDO extensions, you could also take a look at prepared statements
with an integer, you might call intval to make sure you actually get an integer.
So, in the end, I would say you should use something that looks like this :
$id = $_GET['id'];
$escaped_id = mysql_real_escape_string($id);
$query = "DELETE FROM `videos` WHERE `videos`.`id` = '$escaped_id'";
// Here, if needed, you can output the $query, for debugging purposes
mysql_query($query);
You're trying to delimit your query string very strangely... this is what you want:
mysql_query('DELETE FROM `videos` WHERE `videos`.`id` ='.$id);
But make sure you sanitize/validate $id before you query!
Edit: And as Pascal said, you need to assign $id = $_GET['id'];. I overlooked that.
In your delete.php you never set $id.
You need to check the value in $_REQUEST['id'] (or other global variable) and ONLY if it's an integer, set $id to that.
EDIT: Oh, also you need to remove the periods before and after $id in the query. You should print out your query so you can see what you're sending to the sql server. Also, you can get the SQL server's error message.
You add extra dots in the string.
Use
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='$id'");
instead of
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` ='.$id.'");
Also check how do you get the value of $id.
Thanks everyone. I used Pascal MARTIN's answer, and it comes to show that I was missing the request ($_GET) to get the 'id' from the precious page, and that some of my query was incorrect.
Here is the working copy:
<?php
include ("login.php");
$id = $_GET['id'];
mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
mysql_select_db ($dbname)
or die("Unable to connect to database");
mysql_query("DELETE FROM `videos` WHERE `videos`.`id` = $id ");
echo ("Video ".$id." has been deleted.");
?>
Thanks again!

Categories