Echoing an SQL Field in PHP - php

I need some help with echoing an SQL field but it keeps showing Resource #4 or does not show anything at all.
My code is
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$myusername=$_POST['myusername'];
session_register("myusername");
$result = mysql_query("SELECT statsight from playerinfo WHERE username = 'myusername'") or die(mysql_error());
$row = mysql_fetch_array($result);
if(!session_is_registered('myusername')){
header("location:mainlogin.php");
}
echo $row['statsight'];
?>
<html>
<body>
Login Successful
<form name="form2" method="post" action="stat.php">
Stat1: <?php echo "<td>".$row['statsight']."<td>"?>
<input type="submit" value="+">
</form>
</body>
</html>
And it does not show anything. It only shows Stat1: with the + button.
The value of statsight in the database is 3 if it matters, and the myusername information comes from a form.
Got it working using
session_start();
$myusername=$_SESSION['myusername'];

username = 'myusername'
you are not suing variable here.
I am no PHP expert, but this might be the proper way
mysql_query("SELECT statsight from playerinfo WHERE username = ' ". $myusername."'") or die(mysql_error());
Although this is not a proper way, you should be using mechanism of Prepared statements while executing queries.

You will need to use mysql_fetch_assoc instead of mysql_fetch_array So that your field names are brought into the array as keys $row['statsight']

You have to put $ in here '$myusername'
$result = mysql_query("SELECT statsight from playerinfo WHERE username = '$myusername'") or die(mysql_error());

The mysql extension is not recommended anymore. We are meant to use mysqli instead now. While mysqli does support prepared statements, they are not necessary for a simple select like yours. Using the PHP function mysqli_real_escape_string() should be adequate. For an insert query, additional security is required.
The method you are using for sessions is completely deprecated. The proper method is shown in my sample code. I think your reference is so out of date that it is the source of your troubles. I recommend spending some time with a current copy of the official PHP manual.
There are several functions which can be used to handle results of a query which returns a resultset. Here is a partial listing of the
mixed mysqli_result::fetch_array ( [ int $resulttype = MYSQLI_BOTH ] )
// allows you to retrieve an array with numeric keys, an associative array or both
array mysqli_result::fetch_assoc ( void )
// returns an associative array of the current row
object mysqli_result::fetch_object ([ string $class_name [, array $params ]] )
// returns the current row as an object
Mysqli can be used in an object oriented(OO) or procedural way. Most programs now use the OO style. Here is an example (in the OO style).
$mysqli = new mysqli( $host, $username, $password, $dbname );
if ($mysqli->connect_errno)
{
printf( "Connect failed: %s\n", $mysqli->connect_error );
exit();
}
$_SESSION[ 'myusername' ] = $_POST[ 'myusername' ];
$result = $mysqli->query
( "SELECT statsight from playerinfo WHERE username = '".
$mysqli->real_escape_string('myusername' )."'";
$data_array = $result->fetch_assoc();
//$result is a mysqli_result object.
//$data_array is an array of field_name=>value pairs.
if( !isset( $_SESSION[ 'myusername' ])) header( "location:mainlogin.php" );
echo $data_array[ 'statsight' ];
$mysqli->close();
$result->free();
?>
<html>
<body>
Login Successful
<form name="form2" method="post" action="stat.php">
Stat1: <?php echo "<td>".$data_array[ 'statsight' ]."<td>"?>
<input type="submit" value="+">
</form>
</body>
</html>

Related

mysql_query() error in PHP form

So I use to program in PHP my own way and then someone told me to start using his way.
This of course caused me to do a few mistakes.
So this is the code:
<?php
function SignIn()
{
$con = mysqli_connect('localhost','root','avi1574','test');
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
session_start();
if(!empty($_POST['user_w']))
{
$query = mysql_query($con, "SELECT * FROM `Users` where `User` = '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
$row = mysql_fetch_array($query) or die(mysql_error());
if(!empty($row['User']) AND !empty($row['Password'])){
$_SESSION['user_w'] = $row['Password'];
echo "Logged in.";
}
else{
echo "Sorry, wrong password."; } }}
if(isset($_POST['submit'])){
SignIn();
}
?>
<h1>My login page</h1>
<form action="tsql.php" method="POST" >
<input type="text" name="user_w" size="20"></input>
<input type="password" name="pass_w" size="20"></input>
<button type="submit" name="submit">Sumbit</button>
</form>
When I submit the form I get the following error:
Warning: mysql_query() expects parameter 1 to be string, object given in test-main/htdocs/test/tsql.php on line 10
Line 10 is: $query = mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") or die(mysql_error());
Thank you in advance!
Many bad practice in there, let me point out a few things.
$_POST[pass_w]
This doesn't work as pass_w is not a constant. See this article. You must use quotes for the index: $_POST['pass_w'].
You are open to SQL injection and you should use prepared statements.
You also can't mix mysqli and mysql. Don't use mysql_ functions, they are not as secure and deprecated.
To your error message, you are simply trying to put a resource into mysql_query where function expects the query as a string, like SELECT.... You must switch the parameters.
When doing selects for password and username, ensure case sensitivity by using BINARY
and put LIMIT 1 at the end, to ensure only 1 record in return.
SELECT * FROM ... WHERE BINARY username = ... LIMIT 1
Also use some hashing function (not sha1 and not md5 please :-) for the password, with salt!
You should change the function you're using from mysql_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'") to mysqli_query($con, "SELECT * FROMUserswhereUser= '$_POST[user_w]' AND Password = '$_POST[pass_w]'")
(mysqli_query instead of mysql_query).
While you're at it, you should also probably change mysql_fetch_array() to mysqli_fetch_assoc(), for two reasons:
you should use mysql and not mysqli since its deprecated
you're accessing $row's associative array keys, so you need the function to return associative array whild mysqli_fetch_array() returns numeric keys.
Many bugs
User = '$_POST[user_w]' should be User = ".$_POST['user_w']."
Here is some links which may be helpful
about mysql functions: http://php.net/manual/en/book.mysql.php
about mysqli functions: http://php.net/manual/en/book.mysqli.php
Mysql functions is the original function while Mysqli is the extension of Mysql functions
$query = mysql_query($con, "SELECT * FROM `Users` where User = '".$_POST['user_w']."' AND Password = '".$_POST['pass_w']."'");
but read the solution from DanFromGermany, because I gonna point out the same mistake, but as he already mention so no point,
Thanks

Convert to mysqli Prepared Statements from Procedural ones

I need help with the follow code to change it from Procedural to Prepared Statement. I will do my best to code it:
Default procedural script MYSQLI default
<?php
$conn = mysqli_connect ('localhost', 'gggggg', 'gggggg') ;
mysqli_select_db ($conn, 'ggggg');
$anti_injection = mysqli_real_escape_string($_GET['user']);
$sql = "SELECT * FROM profiles WHERE username =".$anti_injection);
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($sql)) {
$username = stripslashes($row['username']);
$age = stripslashes($row['age']);
$gender = stripslashes($row['gender']);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
CATEGORY <?php echo $username; ?>
TITEL <?php echo $age; ?>
CONTENT <?php echo $sex; ?>
</body>
</html>
<?php
}
?>
#
NOW MY CHANGES TO STATEMENTS HOPE IT WORKS
#
$query = $sql->prepare("SELECT * FROM profiles WHERE `username`=?")
$prep->bind_param("s",$anti_injection);
$prep->execute();
Thats all I know for the SELECT in a safe mode but then with the MYSQLI_FETCH_ARRAY I really dont know it it will work and hopefully if there is a chance to keep the script the way I like with the echos between the HTML BODY page
Some Example On How it must be done?
First off, I highly recommend you not mix procedural with objects. It will get confusing much faster that way. Consider using the mysqli object instead.
$mysqli = new mysqli('localhost'...);
Second, you're close but, as I said, you're mixing objects and procedural so the way you've changed it won't work. Plus you're bouncing variables all over the place (if you ran your changes raw it would fail). Assuming you switch to the mysqli object as outlined above, you can do this
$prep = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?");
$prep->bind_param("s",$anti_injection);
$prep->execute();
Now, the next part is tricky. You have to have mysqlnd installed to do this but it's the best way to get your results back. If you run this and get an error about get_result being missing, you're not running mysqlnd
$result = $prep->get_result();
while($row = $result->fetch_array()) {
//Your HTML loop here
}
I provide a script, based on yours, that i have commented, tested, and uses procedural 'mysqli'. Hopefully, it will clarify things.
<?php
/* (PHP 5.3.18 on XAMPP, windows XP)
*
* I will use the procedural 'mysqli' functions in this example as that is
* what you seem familiar with.
*
* However, the 'object oriented' style is preferred currently.
*
* It all works fine though :-)
*
* I recommend PDO (PHP Data Objects) as the way to go for Database access
* as it provides a 'common' interface to many database engines.
*/
// this is an example 'select' parameter -- how this value gets set is up to you...
// use a form, get parameter or other, it is not important.
$bindparamUsername = 'user_2'; // example!!!!
// connect to the database...
$dbConnection = mysqli_connect('localhost', 'test', 'test'); // connect
mysqli_select_db($dbConnection, 'testmysql'); // my test database
// the SQL Query...
// the '?' is a placeholder for a value that will be substituted when the query runs.
// Note: the ORDER of the selected Columns is important not the column names.
//
// Note: The number of selected columns is important and must match the number of
// 'result' bind variables used later.
$sql = "SELECT username, age, gender FROM profiles WHERE username = ?";
// DB engine: parse the query into an internal form that it understands
$preparedQuery = mysqli_prepare($dbConnection, $sql);
// bind an actual input PHP variable to the prepared query so the db will have all required values
// when the query is executed.
//
mysqli_stmt_bind_param($preparedQuery, 's', $bindparamUsername);
// run the query...
$success = mysqli_execute($preparedQuery);
// You can only bind which variables to store the result columns in AFTER the query has run!
//
// Now bind where any results from the query will be returned...
// There must be as many 'bind' variables as there are selected columns!
// This is because each column value from the query will be returned into the
// 'bound' PHP variable.
//
// Note: You cannot bind to an array. You must bind to an individual PHP variable.
//
// I have kept the same names but they are only of use to you.
$fetchedRow = array( 'username' => null,
'age' => null,
'gender' => null);
/*
* Note: order of columns in the query and order of destination variables in the 'bind' statement is important.
*
* i.e. $fetchedRow[username] could be replaced with variable $firstColumn,
* $fetchedRow[age] could be replaces with variable $secondColumn
* and so on...
*
* There must be as many bind variables as there are columns.
*/
mysqli_stmt_bind_result($preparedQuery, $fetchedRow['username'],
$fetchedRow['age'],
$fetchedRow['gender']);
/*
* Note: if you use the 'Object Oriented' version of 'mysqli': All of this is 'hidden'
* but still happens 'behind the scenes'!
*
*/
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
CUSTOM HTML FOR A NICE DESIGN I WANT TO KEEP THE SAME DESIGN LAYOUT ETC...
<?php // each 'fetch' updates the $fetchedRow PHP variable... ?>
<?php while (mysqli_stmt_fetch($preparedQuery)): ?>
<br />
CATEGORY <?php echo $fetchedRow['username']; ?>
<br />
TITEL <?php echo $fetchedRow['age']; ?> <br />
CONTENT <?php echo $fetchedRow['gender']; ?> <br />
<?php endwhile ?>
</body>
</html>
If you'r learning I encourage you to use Object Oriented Style
The Manual is the first resource where you can find the most accurate information. Following your example:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//Here you avoid the warning undefine variable if $_GET['user'] ins't set
$user = isset($_GET['user']) ? $_GET['user'] : NULL;
$row = array();
//Checking if $user is NULL
if(!empty($user)){
// Prepared statement, stage 1: prepare
if (!($stmt = $mysqli->prepare("SELECT * FROM profiles WHERE `username`=?"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("s", $user)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
//Fetching the result
$res = $stmt->get_result();
$row = $res->fetch_assoc();
/* explicit close recommended */
$stmt->close();
}else{
//do this code if $user is null
}
//Printing out the result
echo '<pre>';
print_r($row);
echo '</pre>';
you can do it like that
$link = mysqli_connect("localhost", "my_user", "my_password", "db"); //Establishing connection to the database , this is alias of new mysqli('')
$query="SELECT * FROM profiles WHERE `username`=?";
$stmt = $link->prepare($query);
$stmt->bind_param("s",$anti_injection); // binding the parameter to it
$stmt->execute(); //Executing
$result = $stmt->get_result();
while($row = $result->fetch_array(MYSQLI_ASSOC)) // we used MYSQLI_ASSOC flag here you also can use MYSQLI_NUM or MYSQLI_BOTH
{
//Do stuff
}

Beginner MySQL database search - not getting results

I am having my first attempts to a search engine:
I have a database called "global" and a table called "mpl" which contains 11 columns (Named: Customer, Part No, Descripton, Country Of Origin, and several other) with multiple rows for parts.
What i aim to do with the code below - is to get the Description and Country Of Origin displayed for the Part No the user has entered to the search field.
Form:
<form action="search.php" method="post">
<input type="text" name="find" /><br />
<input type="submit" value="Search" /> </form>
And the PHP:
$host = "localhost";
$dbuser = "root";
$dbpass = " ";
$db = "global";
$con = mysql_connect($host, $dbuser, $dbpass);
if(!$con){ die(mysql_error());
}
$select = mysql_select_db($db, $con);
if(!$select){ die(mysql_error());
}
$item = $_REQUEST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
while($row = mysql_fetch_array($data)){
echo $row['Description']. "<br>";
echo $row['Country Of Origin']. "<br><p>";
}
?>
Can someone tell me what am i doing wrong? Once i enter anything to my form 'find' - i get no results. If i run the search using LIKE instead of "=" with no value - it displays a bunch of Descriptions and Country of origin - this means i have connected to my DB correctly. This is driving me nuts..I feel i have messed up the mysql_query() part somehow - but i can't figure out which part.
You are using the wrong characters to escape the Part No column name in your query. Escape them with the backticks (`) and it should be fine.
$data = mysql_query("SELECT * FROM mpl WHERE `Part No` ='".$item."'");
Also, you should validate the user's query to prevent SQL injection.
A lot of people here have already pointed out possible and actual errors in your code, but here's the combined solution. Firstly I converted your code to mysqli which is the correct way of connecting to a mySQL database. The way you were connecting is out of date, and not recommended. Secondly I added some code to stop sql injection. Thirdly, I changed 'Part No' to `Part No``(ignore the second back tick) in your query.
<?php
$mysqli = new mysqli('localhost', 'root', DB_PASSWORD, 'global');
/* check connection */
if ($mysqli->connect_error)
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
/* escape string from sql injection */
$item = $mysqli->real_escape_string($_POST['find']);
/* query database */
$result = $mysqli->query("SELECT * FROM `mpl` WHERE `Part No` = '".$item."'");
while ($col = $result->fetch_array(MYSQLI_ASSOC))
echo '<p>' . $col['Description'] . '<br />' . $col['Country Of Origin'] . '</p>';
$result->close();
/* don't forget to close the connection */
$mysqli->close();
?>
What if you change:
$item = $_REQUEST['find'];
to
$item = $_POST['find'];
Also some function like mysql_select_db() are deprecated and going to be removed. See:
http://php.net/manual/en/function.mysql-select-db.php
Try changing this potion.
$item = $_REQUEST['find']; $data = mysql_query("SELECT * FROM mpl WHERE 'Part No' ='".$item."'");
to this
$item = $_POST['find'];
$data = mysql_query("SELECT * FROM mpl WHERE Part No ='$item'");
do something like this in your request to remove any possible whitespaces and normalize to upper case for select string.
$item = strtoupper(trim($_REQUEST['find']));
And do this in your SQL: to normalize as well.
$data = mysql_query("SELECT * FROM mpl WHERE UPPER(TRIM('Part No')) ='".$item."'");
You are basically not getting an exact match on your where clause
First off, I agree with Quentin; you should be using a database API like PDO or Mysqli. Secondly, it looks like people can search for parts by their part numbers or descriptions. Assuming the part numbers are numeric and the descriptions are strings... check the type of input and run the query accordingly.
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "global";
// Establish a database connection and select one.
// Try using one of the database API's.
// Then compose your sql by checking for the type of input from the form.
// Since your request method is a POST, then just look in the `_POST` superglobal.
$item = $_POST['find'];
if( is_numeric($item) ){
$sql = "SELECT * FROM mpl WHERE 'Part No' = {$item}";
}else{
$sql = "SELECT * FROM mpl WHERE 'Description' LIKE '%{$item}%'";
}
// Then perform the query.

Jquery/PHP ajax login system

I'm setting up a blog type page for my business. Brand new to MySQL and PHP. Set up this login system. For some reason have no idea why the login is dropping. Suppose to check for errors then return 'good' through php if the email and password is right. If php returns good then it's suppose to redirect to the blog page.
Been dealing with this for a few months need desperate help please. Thank you.
Here is the php code that goes along with the jquery.
Link to test site is here.
test.toddprod.com/login
Would really appreciated the help.
Thanks
<?php
#fake mysql connection first
DEFINE ('DB_USER','usernamegoeshere');
DEFINE ('DB_PASSWORD','passwordhere');
DEFINE ('DB_HOST','hostnamehere');
DEFINE ('DB_NAME','andtheotherthinghere');
$dbc = mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
$db = mysql_select_db(DB_NAME, $dbc) or die('Could not select database.'.mysql_error());
$e = $_POST['email'];
$pass = $_POST['pass'];
$q = 'SELECT user_id from toddprod where email="'.$e.'" and pass= SHA1("'.$pass.'")';
$r = mysql_query($db, $q);
if( mysql_num_rows($r)==1 ){
setcookie ( 'user_id', $r);
setcookie ( 'email', '$e');
setcookie ( 'logged-in', 'true');
echo 'good';
}
else if (mysql_num_rows($r)==0) {
echo 'Your '.$e.' with password '.$pass;
};
mysql_close ($db);
?>
Umm there's a number of things I see wrong here...
First of all your query should be sanitized...
$email = mysql_real_escape_string ($_POST['email']); // escape the email
$pass = SHA1(mysql_real_escape_string ($_POST['pass'])); // escape and encrypt the pass
// now you can put it into the query safely
$query = "SELECT user_id from toddprod where email = '$email' and pass = '$pass' ";
Next you're executing the query wrong, the mysql_query function takes two arguments, the query and the database connection. You're passing the wrong arguments, you're passing the query and the result of the mysql_select_db function which is just a boolean value. So you have to $dbc not $db into that query, and even then you're passing the arguments in the wrong order. The query goes first, than the connection. So it should be...
$result = mysql_query($query, $dbc);
Next you're trying to set the return value from the mysql_query function as your cookie but that value is a resource, not the userid that you need. You have to actually read the value from the resource like this.
$row = mysql_fetch_array($result);
$userid = $row["user_id"];
setcookie('user_id', $userid);
Moving on... when you're setting the email cookie, you have the variable in single quotes, so the cookie will actually contain $e and not the actual email because single quotes store strings litterly (without parsing the variables). So you should either use double quotes, or no quotes at all. So either one of the following is fine...
setcookie('email', "$e");
setcookie('email', $e);
Last but not least, you should not have the semicolon at the end of your if-statement, and you again you need to pass the connection not the database-selection result into the mysql_close function, so it should be
mysql_close($dbc);
There, hope this gets you somewhere, try out these changes and if the problem persists i'd be happy to help you further.
Here are links that will help you out:
http://www.php.net/manual/en/function.mysql-query.php
http://www.php.net/manual/en/function.mysql-fetch-array.php
http://www.php.net/manual/en/function.mysql-real-escape-string.php
Edit:
Here, I have fixed the code according to the problems I found. Try it out, I could not test it so it might have some small syntax errors here and there, but it should give you something to compare with. Also for the future, I would suggest that you name your variables semantically/properly so it's easier for others to pickup and it will also keep you from getting confused like you were passing $db instead of $dbc into a few of your functions.
<?php
// keep the function names in lowercase, no reason, just looks better to me
define('DB_USER', 'usernamegoeshere');
define('DB_PASSWORD', 'passwordhere');
define('DB_HOST', 'hostnamehere');
define('DB_NAME', 'andtheotherthinghere');
// connect to the mysql server
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die ('Could not connect to MySQL');
// select the database, you don't need to store the result, it just returns true or false
mysql_select_db(DB_NAME, $conn) or die('Could not select database.' .mysql_error());
// escape the input
$email = mysql_real_escape_string($_POST['email']);
$pass = sha1(mysql_real_escape_string($_POST['pass']));
// create the query
$query = "SELECT user_id FROM toddprod WHERE email = '$email' AND pass = '$pass'";
// execute the query
$result = mysql_query($query, $conn);
$usercount = mysql_num_rows($result);
if($usercount == 1){
// read the results and get the user_id
$row = mysql_fetch_array($result);
$userid = $row['user_id'];
// set the cookies
setcookie('user_id', $userid);
setcookie('email', $email);
setcookie('logged-in', 'true');
// echo success message
echo 'good';
}elseif($usercount == 0) {
echo "You're $email with password $pass";
}
mysql_close($conn);
?>
First things first, you MUST sanitise user input with mysql_real_escape_string():
$e = mysql_real_escape_string ($_POST['email']);
$pass = mysql_real_escape_string ($_POST['pass']);
Read up a bit on SQL injection, you'll be very glad you did.
As for the main problem, could you provide a bit more context? How are you checking to see if the user is logged in?

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