multiple mysqli delete codes on one PHP page - php

I am still learing PHP and MySQLI and was wondering if it is possible to host multiple MySQLI delete queries on a single php page and have the url act on the corresponding query without confusion. I have this code here, I have search the web for an answer for 3 days but nothing I found seemed to be what I was looking for. Any help or properly described examples based on my code would be greatly appreciated.
my Code is:
<?php
session_start();
include ('dbconnect.php');
$userr = $_SESSION['usr_id'];
$uid=$_GET['pid'];
$pid=$_GET['phid'];
$user_id=$_GET['user'];
$fileID=$_GET['file'];
if($userr==$uid && $pid==$fileID){
echo "ERROR No. 9B2AP";
}else{
mysqli_query($con,"delete from images where userID='$uid' AND PhotoID='$pid'") or die (mysqli_error());
header ("location: /viewImage.php?pid=$uid");
}
if($userr==$user_id && $fileID==$pid){
echo "ERROR No. 39V41";
}else{
mysqli_query($con,"delete from music where userID='$user_id' AND Record_ID='$fileID'") or die (mysqli_error());
header ("location: /users/music-gallery/$user_id");
}
?>
No matter how many times I rewrite this code, when i delete an image or song using the code on this page, It redirects me only to the /users/music-gallery/ instead of the proper associated page. How might I get this fixed? Like I said, I am fairy new to PHP and MySQLI and any suggestions I believe should be described in details so I might be able to understand and comprehend how I made the mistake and I to fix and prevent it from happening again in later code. Please and Thank-you.
-M.S

For security reasons don't do this:
// Consider escaping the incoming data for better security
$uid=$_GET['pid'];
$pid=$_GET['phid'];
// ...
Since you are using MySQLi you can use this to escape your data:
$uid = mysqli_real_escape_string($con, $_GET['pid']);
You can use FILTERS to check input data type:
// If you are expecting an `INT` from $_GET['pid']
if (filter_var($_GET['pid'], FILTER_VALIDATE_INT))
{
echo 'pid is an int';
}
else
{
echo 'pid is not an int';
}
more on filters here.
The best of all, use prepared mysqli statements with stmt:
// prepare the statement
$stmt = $con->prepare("delete from images where userID=? AND PhotoID=?");
// bind variables to the '?' and set types --> `i` = integer
$stmt->bind_param("ii", $_GET['pid'], $_GET['phid']);
// execute query
$stmt->execute();
// Do the same for the next query
more on prepared statements here.
To solve your problem:
To exit a program right after a header you need to use exit(); after each header like this:
header ("location: /viewImage.php?pid=$uid");
exit();
For instance:
header ("location: /viewImage.php?pid=$uid");
// this line of code gets exucuted
// this too
// ...
header ("location: /viewImage.php?pid=$uid");
exit();
// Nothing gets executed as program terminates and redirects

Related

PHP SQL query doesnt return a result

I have a button in a webapp that allows users to request a specially formatted number. When a user click this button 2 scripts run. The first that is fully functional, looks at a number table finds the largest number and increments it by 1. (This is not the Primary Key) the second script which is partially working gets the current date and runs a SQL query to get which period that date falls in. (Periods in this case not always equaling a full month) I know this script is at least partially working because I can access the $datetoday variable called in that script file. However it is not returning the requested data from the periods table. Anyone that could help me identify what I am doing wrong?
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods where '$datetoday' BETWEEN p_start AND p_end";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
$pnum = $row;
mysqli_stmt_close($stmt);
}
If it helps any one I published my code to https://github.com/cwilson-vts/Quote-Appliction
So first off, I do not use msqli and never learned it. However, I believe I get the gist of what you want to do. I use PDO because I FEEL that it is easier to use, easier to read and it's also what I learned starting off. It's kinda like Apple vs. Samsung... no one product is exactly wrong or right. And each have their advantages and disadvantages. What I'm about to provide you will be in PDO form so I hope that you will be able to use this. And if you can't then no worries.
I want to first address one major thing that I saw and that is you interlacing variables directly into a mysql statement. This is not considered standard practice and is not safe due to sql injections. For reference, I would like you to read these sites:
http://php.net/manual/en/security.database.sql-injection.php
http://php.net/manual/en/pdo.prepared-statements.php
Next, I'm noticing you're using datetime as a variable name. I advise against this as this is reserved in most programming languages and can be tricky. So instead, I am going to change it something that won't be sensitive to it such as $now = "hello world data";
Also I'm not seeing where you would print the result? Or did you just not include that?
Another thing to consider: is your datetime variable the same format as what you are storing in your db? Because if not, you will return 0 results every time. Also make sure it is the right time zone too. Because that will really screw with you. And I will show you that in the code below too.
So now on to the actual code! I will be providing you with everything from the db connection code to the sql execution.
DB CONNECTION FILE:
<?php
$host = '127.0.0.1';
$user = 'root';
$pw = '';
$db = 'test'; // your db name here (replace 'test' with whatever your db name is)
try {
// this is the variable will call on later in the main file
$conn = new PDO("mysql:host=$host;dbname=$db;", $user, $pw);
} catch (PDOException $e) {
// kills the page and returns mysql error
die("Connection failed: " . $e->getMessage());
}
?>
The data file:
<?php
// calls on the db connection file
require 'dbconfig.php';
// set default date (can be whatever you need compared to your web server's timezone). For this example we will assume the web server is operating on EST.
date_default_timezone('US/Eastern');
$now = date("Ymd");
// check that the $now var is set
if(isset($now)) {
$query = $conn->prepare("SELECT p_num FROM periods WHERE p_start BETWEEN p_start AND :now AND p_end BETWEEN p_end AND :now");
$query->bindValue(':now', $now);
if($query->execute()) {
$data = $query->fetchAll(PDO::FETCH_ASSOC);
print_r($data); // checking that data is successfully being retrieved (only a troubleshooting method...you would remove this once you confirm it works)
} else {
// redirect as needed and print a user message
die("Something went wrong!");
}
$query->closeCursor();
}
?>
Another thing I want to mention is that make sure you follow due process with troubleshooting. If it's not working and I'm not getting any errors, I usually start at the querying level first. I check to make sure my query is executing properly. To do that, I go into my db and execute it manually. If that's working, then I want to check that I am actually receiving a value to the variable I'm declaring. As you can see, I check to make sure the $now variable is set. If it's not, that block of code won't even run. PHP can be rather tricky and finicky about this so make sure you check that. If you aren't sure what the variable is being set too, echo or print it with simply doing echo $now
If you have further questions please let me know. I hope this helps you!
I think I know what I was doing wrong, somebody with more PHP smarts than me will have to say for sure. In my above code I was using mysqli_stmt_store_result I believe that was clearing my variable before I intended. I changed that and reworked my query to be more simple.
<?php
include 'dbh.inc.php';
$datetoday = date("Ymd");
$sql = "SELECT p_num FROM periods WHERE p_start <= $datetoday order by p_num desc limit 1";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../quote.php?quotes=failed_to_write");
exit();
} else {
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while( $row = mysqli_fetch_assoc($result)) {
$pnum = $row['p_num'];
echo $pnum;
}
mysqli_stmt_close($stmt);
}
Thanks to #rhuntington and #nick for trying to help. Sorry I am such an idiot.

Adding a 'check username' to registration form PHP

Please could someone give me some much needed direction...
I have a registration form, however I need to add a condition that if the username is already in the table, then a message will appear. I have a had a few goes except it just keeps adding to the SQL table.
Any help would be much appreciated. Here is my current code:
Thanks in advance!
<?php
session_start();session_destroy();
session_start();
$regname = $_GET['regname'];
$passord = $_GET['password'];
if($_GET["regname"] && $_GET["regemail"] && $_GET["regpass1"] && $_GET["regpass2"] )
{
if($_GET["regpass1"]==$_GET["regpass2"])
{
$host="localhost";
$username="xxx";
$password="xxx";
$conn= mysql_connect($host,$username,$password)or die(mysql_error());
mysql_select_db("xxx",$conn);
$sql="insert into users (name,email,password) values('$_GET[regname]','$_GET[regemail]','$_GET[regpass1]')";
$result=mysql_query($sql,$conn) or die(mysql_error());
print "<h1>you have registered sucessfully</h1>";
print "<a href='login_index.php'>go to login page</a>";
}
else print "passwords don't match";
}
else print"invaild input data";
?>
User kingkero offered a good approach. You could modify your table so that the username field is UNIQUE and therefore the table cannot contain rows with duplicate usernames.
However, if you cannot modify the table or for other reasons want to choose a different approach, you can first try to run a select on the table, check the results and act accordingly:
$result=mysql_query('SELECT name FROM users WHERE name="'.$_GET['regname'].'"');
$row = mysql_fetch_row($result);
You can then check $row if it contains the username:
if($row['name']==$_GET['regname'])
If this statement returns true, then you can show the user a message and tell him to pick a different username.
Please note
Using variables that come directly from the client (or browser) such as what might be stored in $_GET['regname'] and using them to build your SQL statement is considered unsafe (see the Wikipedia article on SQL-Injections).
You can use
$regname=mysql_escape_string($_GET['regname'])
to make sure that its safe.
Firstly, there is some chaos on the second line:
session_start();session_destroy();
session_start();
Why you doing it? Just one session_start(); needed.
Then you can find users by simple SQL query:
$sql="SELECT * FROM users WHERE name = '$regname'";
$result=mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
//...echo your message here
}
When you got it, I suggest you to rewrite your code with use of PDO and param data binding, in order to prevent SQL injections and using of obsolete functions.

PHP Select Value & Redirect With If Statement

I'm trying to create a php scipt that checks if members are verified as they land on a page. If they are not they get redierected to login with an error message & instructions. So on the page I have this code:
<?php
if (loggedin()) {
$check_active = "SELECT active FROM members WHERE username == '$username'";
$active = mysql_query($check_active);
if ($active < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}
}
?>
It is redirecting the user back to the login page but it doing it whether they are active or not. The values for active members are 0(not verified) & 1(verified). Is htere something wrong in the script I'm using?
Thank You
You'll need to handle the $active result and put it into a PHP variable/array. $active as it is in your code is simply a resource (see here) Try this:
$active = mysql_query($check_active); // run query and return resource
$row = mysql_fetch_assoc($active); // put resource data into php array
if ($row['active'] < 1) {
header("Location: login.php?verify=true");
} else {
exit();
}
Please don't use old mysql, use mysqli_ or read topic on http://php.net/manual/en/function.mysql-query.php.
Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
You aren't fetching the data correctly after the query.
Right after you do the the mysql_query function. Try this:
$output = mysql_fetch_assoc($active);
$active_result = $ouput['active'];
Don't know if it might work.
And add a little more security for SQL injection there.
And use MySQLi instead since you aren't keen on preventing SQL injection yourself.

PHP MYSQL Warning: mysql_query() expects parameter 1 to be string, resource given in

<?php
include 'connect.php';
include 'header.php';
$page = "signup.php";
// receive the invite code:
$code = $_POST['code'];
$sql = "SELECT codes FROM invites WHERE codes='$code'";
// check the table for matching codes
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) {
// end any previously defined sessions.
session_start();session_unset();session_destroy();
// start a new session
session_start();
// define the session variable.
// this allows us to check if it's set later and is required for
// the script to run properly.
$code = $_POST["code"];
mysql_query("DELETE FROM invites WHERE codes='$code'");
header('Location: '.$page);
exit;
} else {
echo "Invite invalid. Please try again later.";
echo $code;
}
include 'footer.php';
?>
I am trying to implement an invite system to a webpage I am working on. However when trying to evaluate if there is a row containing the invite code I keep either getting nothing or this warning. The warning in this case but if I change the if state to ==1, it allows everyone regardless of code and ==0 does throws different errors.
if (mysql_query($result)) {
Try mysql_num_rows there.
There are a few things wrong here.
1) SQL Injection vulnerabilities, don't ever pass a superglobal $_POST or $_GET or any other user-supplied variable directly inside your query!
Use at minimum mysql_real_escape_string() to the variable before letting it into the query, or better look into parametrized queries, it's the best way to avoid SQL vulnerabilities
2)
$result = mysql_query($sql);
// check if the request returned 1 or 0 rows from the database
if (mysql_query($result)) ....
This doesn't check if request returns 1 or 0 rows, you should use mysql_num_rows() here instead
if(mysql_num_rows() == 1) //or whatever you need to check
3)
session_start();session_unset();session_destroy();
// start a new session
session_start();
session_start() should be called before anything in your page. Don't know why this redundancy of calling, unsetting, destroying, recalling it here. If you want another id, just use session_regenerate_id();
And as already said by other, use some error reporting in your query, something like
$result = mysql_query($sql) or die(mysql_error())
to actually see what's failed, where and why.
Problem is your query. First of all check your statement and use this :
$result = mysql_query($sql) or die(mysql_error());
instead of this
$result = mysql_query($sql);
So, you can see are there any error at your SQL query .

php form errors

hello im trying to set custom errors. i got a form. actions to post.php i dont want form to go post.php for errors i need to set errors in same page. i tried
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
<?
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
}
if(! $sonuc) {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
this always shows Yeni icerik basarili bir sekilde eklendi. this.
help me plx
Your query is valid and it inserts data sucsesfully, therefore MySql_Query() returns true, which in turn "triggers" the first if, but not the second.
See documentation for return values of MySql_Query.
If you want validation you have to write it.
also: your two if statements can be refactored into one. Look at the if/else syntax
If you're trying to have your errors show up in the submitting form just move your post.php code into your form page and condition it like this:
<?php
if(isset($_POST['baslik'])) {
$sql = "
INSERT INTO yazilar (baslik, spot, spot_kisa, spot_resim, spot_resim_isim, icerik, kategori, tiklanma, eklemetarihi)
VALUES
('$_POST[baslik]','$_POST[spot]','$_POST[spot_kisa]','$_POST[spot_resim]','$_POST[spot_resim_isim]','$_POST[icerik]','$_POST[kategori]','$_POST[tiklanma]','$_POST[tarih]')
";
$sonuc = mysql_query($sql);
if ($sonuc) {
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
exit;
}
else {
$error = "<p class='msg warning'>Ekleme basarisiz oldu.</p>";
}
}
?>
// form code here
<?php if(isset($error)) { echo $error; } ?>
// around where you'd like the error to display
Now if the action is a success the success message will display with nothing else, otherwise the form will be redisplayed with the error message where you positioned it. Also, please see soulmerge's comments on SQL injection, it's a serious security risk that can be easily avoided.
replace
$sonuc = mysql_query($sql);
with this
$sonuc = mysql_query($sql) or die(mysql_error());
is there any errors?
is it possible that your table fields do not match that ones you insert?
What is wrong about it? The return values of mysql_query() is a boolen for INSERT queries, which is true if the operation was successful. Have you tried inserting invalid values (like a text that is too long)? That should generate a warning and return false.
But what bothers much more is that your code is vulnerable to SQL injection. Please read up on sql injections on php.net how to fix that problem.
try this
$sonuc = mysql_query($sql);
<?php
if($sonuc !== false){
echo ("<p class='msg done'>Yeni icerik basarili bir sekilde eklendi.</p>");
} else {
echo ("<p class='msg warning'>Ekleme basarisiz oldu.</p>");
}
?>
EDIT: When you need a validation instead of a check if the query worked check this http://www.php-mysql-tutorial.com/wikis/php-tutorial/form-validation-using-php.aspx
Try this:
if ($sonuc !== false){...
See php manual entry
Jan Hančič has already answered the question but as a side note:
Don't use POST data directly on your queries it will end badly trust me!!

Categories