PHP - $GET and delete from MySQL - php

I have an a href which looks like that: Delete
And file delete-news.php is as follow:
<?php
if(isset($_GET["?deleteID='.$id."]))
{
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
But it is returning GET NOT SET. What I'm doing wrong?

Use this, and for god's sake escape your inputs.
if(isset($_GET['deleteID'])) {
$result = mysql_query("DELETE FROM `news` WHERE id='".mysql_real_escape_string($_GET['deleteID']). "'");
echo mysql_error();
if($result)
echo "succces";
} else {
echo 'GET NOT SET';
}

$_GET will have each element of the GET variables already broken down, so no need to include the URL data. So, in your example, the link ?deleteID=123 would produce $_GET['deleteID'].
Try using that, but also remember to sanitize the values you receive in from URLs. If it's going to be a numeric value, I suggest casting it:
$deleteID = (int)$_GET['deleteID'];

Please also note that changes to the system should only happen via POST, and never GET. Otherwise (for example), you might get a spidering bot that deletes your whole site. See this post for more references:
https://stackoverflow.com/questions/679013/get-vs-post-best-practices

You need to check $_GET for just deleteID. Later, reference it as $_GET['deleteID']. Also, call mysql_real_escape_string() on $_GET['deleteID'] to retrieve your query parameter $id.
if(isset($_GET["deleteID"]))
{
$id = mysql_real_escape_string($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }

Try this instead:
<?php
if(isset($_GET['deleteID']))
{
$id = intval($_GET['deleteID']);
$result = mysql_query("DELETE FROM `news` WHERE id='$id'");
echo mysql_error();
if($result) echo "succces";
} else {
echo "GET NOT SET";
}
?>
Note that I'm making the given deleteID into an int, meaning that values other than some form of number will become 0.
Also, you can't wrap a table- and/or column name with ' - backticks are the way to go!

<?php
if(isset($_GET["deleteID"]))
{
$id = ($_GET['deleteID']);
$result = mysql_query("DELETE FROM news WHERE id='".mysql_real_escape_string($id)."'");
echo mysql_error();
if($result)
echo "succces";
}
else { echo "GET NOT SET"; }
?>
is correct one

You obtain GET NO SET, because the $_GET associative array does not contain ?deleteID='.$id.
In order for you to obtain the id, you need to so something like this:
$id = $_GET['deleteID'];
Also
$result = mysql_query("DELETE FROM 'news' WHERE id='$id'");
That is very unsafe as it allows SQL injections. Instead, do:
$query = sprintf("DELETE * FROM news WHERE id=%d",
mysql_real_escape_string($id),
$result = mysql_query($query);
I hope this helped.

Related

How to resolve Undefined index: Notice when displaying database retrieved value in php

I'm getting an undefined index notice, but can't figure out how to fix it.
Below is the code which is generating the error:
<?php
include 'dbconfig.php';
$id;
if(isset($_POST['Tid']))
{
$id=$_POST['To_ID'];
echo "selected value:".$id;
$query="select 'ID','Name' from where ID='$id'";
$result=sqlsrv_query($conn,$query);
$a=sqlsrv_num_rows($result);
echo $a;
if(!$result)
{
echo "Query execution failed";
}
else {
while($row = sqlsrv_fetch_array($result))
{
print_r($row['ID'].$row['Name']);
}
}
}
else {
echo "Post variable not set";
}
I am getting error on the line here-
print_r($row['ID'].$row['Name']);
And also i am verified database columns the columns ID and Name is present in the database and the select query is also executing well when i tried seperately.
Even though the filed name ID and Name exists i am getting Undefined Index ID and Name Error.
Please help me to resolve this error.
Thanks in advance.
You are using the wrong kind of quotes and you are missing the table name:
$query="select 'ID','Name' from where ID='$id'";
Should be:
$query="select ID,Name from table_name where ID='$id'";
Or, if the column names need to be quoted you need block-quotes in sql server:
$query="select [ID],[Name] from [table_name] where [ID]='$id'";
Also note that you have an sql injection problem. Ideally, you should use a prepared statement, but if the value of the ID is an integer, you can also do:
$id = (int) $_POST['To_ID'];
$query = "select ID,Name from table_name where ID='$id'";
try this:
$query="select ID,Name from where ID='$id'";
$result=sqlsrv_query($conn,$query);
$a=sqlsrv_num_rows($result);
echo $a;
if(!$result)
{
echo "Query execution failed";
} else {
for($i = 0; $i < $a; $i++)
{
print_r($row[$i]['ID'].$row[$i]['Name'].'<br/>');
}
}
} else {
echo "Post variable not set";
}

How can I SELECT field FROM table WHERE id=variable?

I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.

Not inserting where i expected

In a mysql table, i have 3 fields. user_to, user_from and id. The variables are all correct and should be inserting the correct data.
When a button is clicked, named 'poke', it should insert the cookie that stores the session of who did it and the person who was poked. It doesn't seem to be inserting and I am stuck :(
$cookie = $_SESSION['user_login'];
//Poke code
if (#$_POST['poke']) {
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$username' && user_from='$added_by'");
$num_poke_found = mysql_num_rows($check_if_poked);
if ($num_poke_found == 1) {
echo "Come on! Give the guy a chance!";
}
else
if ($username == $cookie) {
echo "You cannot Jab yourself.";
}
else
{ $poke_user = mysql_query("INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')") or trigger_error(mysql_error());
echo "$username has been jabbed.";
}
}
You used wrong quotes with fields in MySQL query.
//your wrong variant
"INSERT INTO `pokes` ('user_from', 'user_to') VALUES ('$cookie', '$username')"
//right variant
"INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$cookie', '$username')"
Quotes like ' mean values and quotes like ` mean fields in SQL syntax
<?php
if ($_POST['poke']) {
#ref to the current user
$from = $_SESSION['user_login'];
#ref to the (poked user)
$to = $_POST['poked_user_id'];
if($from == $to){
echo "you cant poke yourself!";
}
else{
#ADVICE: USE PDO OR MYSQLI INSTEAD OF MYSQL
$check_if_poked = mysql_query("SELECT * FROM pokes WHERE user_to='$to' AND user_from='$from'");
if(mysql_num_rows($check_if_poked)){
echo "Come on! Give the guy a chance!";
}
else{
if(mysql_query("INSERT INTO `pokes` (`user_from`, `user_to`) VALUES ('$from', '$to')")){
echo "$to has been jabbed.";
}
else{
trigger_error(mysql_error());
}
}
}
}
?>
This started off as a comment - but it's getting too long to fit.
A session is not the same thing as a username - your post is very confused.
Leaving aside the wrong quotes (which is why your code is not doing what you expect)....
In a mysql table, i have 3 fields. user_to, user_from and id
... in that case you don't need to check if the row already exists - and not create duplicates. Set up a unique index then...
if (#$_POST['poke'] && ($_SESSION['user_login']!===$username)) {
$qry = "INSERT INTO `pokes` (`user_from`, `user_to`)
VALUES (".mysql_real_escape_string($_SESSION['user_login'])
.", '" . mysql_real_escape_string($username) . "')"
if (mysql_query($qry)){
echo "$username has been jabbed.";
} else if (stristr(mysql_error(), 'duplicate')) {
echo "Come on! Give the guy a chance!";
} else {
echo "It's all gone Pete Tong!";
}
} else if ($_SESSION['user_login']!===$username) {
echo "You cannot Jab yourself.";
}
While it's about the same effort for PHP processing, the DB workload is significantly less. This code also prevents some SQL injection attacks, and has error handling. I presume that $username has been created elsewhere and you don't have register_globals enabled.

How to get a value from database for validation purpose in PHP?

I have a user level field in my database that contains either 1 or 2. what I want to do is to get the row that has the username that I inputted that contains level 2. Here is my code:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM order");
while($row=mysql_fetch_array($tbl))
{
if (($row['level']=='2')&&($row['username']==$_POST['user']))
{
echo $row['username']."".$row['garlique']."".$row['rightcee'];
echo $row['oleia']."<br />";
}
else
{
echo $row['username']."".$row['garlique']."".$row['rightcee'];
echo .$row['oleia']."<br />";
}
}
?>
When I tried to test it, an error "unexpected $end" showed. What I think is wrong in my code is the validation if.. ($row['level']=='2').. I don't have any idea how to fix this kind of problem. I am a beginner in php, so if you could help me out, I would appreciate it very much. :)
Close your while loop with }. Syntax error.
I'd like to make a suggestion. If your goal is, as stated, to retrieve the row of the given username that is level 2, your query could do all the work:
// Put the username in a variable, making sure it's safe for SQL by escaping it
$username = mysql_real_escape_string($_POST['user']);
// Grab the row from the table, expecting only a single result
$tbl = mysql_query("SELECT * FROM `order` WHERE `username` = '$username' AND `level` = '2' LIMIT 1");
// Set your row variables
$rows = mysql_fetch_array($tbl);
$row = $rows[0];
if (!$row)
{
// Either not a valid username or the username isn't level 2
}
else
{
// Valid row
}
You forget the last }
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("nnx",$con);
$tbl=mysql_query("SELECT * FROM order");
while($row=mysql_fetch_array($tbl))
{
if (($row['level']=='2')&&($row['username']==$_POST['user']))
{
echo $row['username']."".$row['garlique']."".$row['rightcee']."".$row['oleia'];
echo "<br />";
} else {
echo $row['username']."".$row['garlique']."".$row['rightcee']."".$row['oleia'];
echo "<br />";
}
} // PAY ATTENTION TO THIS!!
?>

PHP Mysql Data Insert

I'm learning PHP from reading the php manual and studying different tutorials. I hit a snag with the mysql_query. I'm trying to insert user data into a database from a form using PHP. The mysql_query should return false because the username doesn't exist in the database yet but according to the result I am getting it is returning true and nothing is being entered into the database. Am I using mysql_query wrong or is using !result incorrect?
$sql = "SELECT * FROM users WHERE username='".$_POST["name"]."'";
$result = mysql_query($sql)
if (!$result) {
$sql = "INSERT INTO USERS (username, email, password) VALUES
('".$_POST["name"]."', '".$_POST["email"]."', '".$passwords[0]."')";
$result = mysql_query($sql);
if ($result) {
echo "It's entered!";
} else {
echo "There's been a problem: " . mysql_error();
}
} else {
echo "There's already a user with that name: <br />";
$sqlAll = "SELECT * FROM users";
$resultsAll = mysql_query($sqlAll);
$row = mysql_fetch_array($resultsAll);
while ($row) {
echo $row["username"]." -- ".$row["email"]."<br />";
$row = mysql_fetch_array($result);
}
}
Jason, you're checking to see if the query has failed or not - not whether it has returned the value 'false' or 'true'. You need to call mysql_fetch_row or similar, then compare the result.
Alternatively you could use the following:
if (mysql_num_rows($result) == 0) {
/* User doesn't exist */
} else {
/* User exists */
}
This will detect if any users have been chosen by your query and - if they have - your user exists already.
Also, you should learn about input sanitisation and SQL Injection. It's a very critical security issue and your script is vulnerable to it. More info here.
A select query which has no result rows STILL returns a result handle. msyql_query() will ONLY return a 'false' value if the query fails due to a syntax error, constraint violation, etc...
Your code should be
$sql = "...";
$result = mysql_query($sql);
if ($result === false) {
die("QUery failed: " . mysql_error());
}
if (mysql_num_rows($result) == 0) {
... user does not exist ...
}
And please please please read up about SQL injection vulnerabilities. Your code has holes wide enough for a truck to drive through.
In this case, $result will be a resource. You should check the number of results with mysql_num_rows().
Never, really, NEVER, use $_POST or any direct user input in a query. Always escape the input, BEFORE using it in a query, with mysql_real_escape_string(), or you'll have opened a serious security issue with SQL Injection.
Ex:
$safe_name = mysql_real_escape_string($_POST["name"]);
$sql = "SELECT * FROM users WHERE username='$safe_name'";
It's not exact.
mysql_query() will also fail and return FALSE if the user does not
have permission to access the table(s) referenced by the query.
In your case you have the permission but the user doesn't exist. So it will return true but the result set returned is empty.
mysql_query will return an empty set if the query returns no data. The query will however not fail.
i solve my problem :
like this
<?php
$username = $_POST['username'];
include('config.php');
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
while($row = mysqli_fetch_array($result)){
echo $row['username'];
echo "</br>";
echo "</br>";
echo "<p><b>Secret Question</b></p>";
echo $row['secret'];
}
?>
</br>
</br>
<form action="forgetaction.php" method="POST">
<p><b>Answer is :</b><p>
<input type="hidden" name="username" value="<?php echo $username; ?>">
<input type="text" name="answer">
</br>
</br>
<input type="Submit" value="Submit">
</form>
and forget action.php like this :
<?php
include('config.php');
$username = $_POST['username'];
echo $username;
$result = mysqli_query($con,"SELECT * FROM persons WHERE username='$username'");
$row = mysqli_fetch_array($result);
if($row['answer'] == $_POST['answer']) {
echo $row['password'];
} else {
echo 'wrong!';
}
?>
thank you all for help .

Categories