How to use PHP Variables in an SQL statement - php

Before anybody says, I will protect myself against SQL injections, right after I fix this error. I am making an app where news reports are submitted to the database. This page is what removes a report from the database.
What I have tried:
Every possible way of adding brackets to the SQL and speech marks. My ICT teacher and I have looked at this for nearly 2 hours and cannot find a fix. I have also searched Google and Stack Overflow but I cannot find an answer.
Ok, so the correct report_id displays when I echo it. When I put the actual id, eg 5, the report is deleted. But when I put $report_id, nothing is deleted.
Please could somebody tell me what correction I have to make to get this to work ?
Here is the code (EDIT: This is the fixed code. I added the hidden field in the form at the bottom, among a few other small changes (like taking out the extra form tag)):
<?php
require_once('authorize.php');
?>
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Football Central - Remove a Report</title>
</head>
<body>
<h2>Football Central - Remove a News Report</h2>
<?php
require_once('img_details_reports.php');
require_once('connect_db_reports.php');
//Assign variables from admin_reports.php using $_GET
$report_id = $_GET['id'];
if (isset($_POST['submit'])) {
if ($_POST['confirm'] == 'Yes') {
$report_id = $_POST['id'];
// Delete the image file from the server
#unlink(IMAGE_UPLOADPATH . $image);
// Connect to the database
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die("Unable to connect to the database.");
// Delete the score data from the database
$query = "DELETE FROM news_reports WHERE report_id = '".$report_id."' LIMIT 1"
or die("mysql_query failed - Error: " . mysqli_error());
mysqli_query($dbc, $query) or die("mysql_query failed - Error: " . mysqli_error());
mysqli_close($dbc);
}
}
//Display form to confirm delete
echo '<p>Are you sure you want to delete the news report?</p>';
echo '<form method="post" action="removereport.php">';
echo '<input type="radio" name="confirm" value="Yes" /> Yes ';
echo '<input type="radio" name="confirm" value="No" checked="checked" /> No <br />';
echo '<input type="hidden" name="id" value="' . $report_id . '" />';
echo '<input type="submit" value="Submit" name="submit" />';
echo '</form>';
echo '<p><< Back to admin reports page</p>';
?>
</body>
</html>

Your are mixing two statements. Just try below.
// Delete the score data from the database
$query = "DELETE FROM news_reports WHERE report_id = ".$report_id;
mysqli_query($dbc, $query) or die("mysql_query failed - Error: " . mysqli_error($dbc));

You are sending the form with post method and retrieving it with get. That can be the source of the problem.
Also you are not sending the id parameter so, there won't be any value for $_get[id] nor $_post[id]

You shouldn't have to wrap the ID in single-quotes, if the ID is a number.
$query = "DELETE FROM news_reports WHERE report_id = '".$report_id."' LIMIT 1"
But that's not the problem. You did not include the ID in your confirmation request, or allow for retrieving the value from a session variable. Add a hidden input box with the id, in your "Display form to confirm delete" section.
(And have a different code branch for confirmation! And a test for an invalid ID! And move this to POST, at the very least!)

You've got
$query = "..." or die(...);
Why?
Also, you've got two form opening tags -- it's not valid to nest forms.
I'm going to assume that the id variable comes in from some source other than the form because there's no form element that submits it.
Finally, make sure to specify get or post in your form. I'd recommend using post, and then change $_GET["submit"] and $_GET["confirm"] to $_POST["submit"] and $_POST["confirm"].

You need to check following things in your code.
Where is your ID element in the form
You have put POST method in form but retrieving data from $_GET, you should change it to $_POST.
Put mysqli_error after mysqli_query statement.
$query = "DELETE FROM news_reports WHERE report_id = ".$report_id;
mysqli_query($dbc, $query); or die("mysql_query failed - Error: " . mysqli_error());
Then check the error from mysql if it does not work.
Hope, it will help you in solving your issue.

Related

HTML PHP (Why does not return value?)

I was actually trying to retrieve the input submit button value. But I don't know why it does not work. Can anyone help me?
When the user click the buttons, the button's value will be send to the next page.
<?php
include('connect.php');
// Create connection
$conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM userauth";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
?>
<html>
<head>
<title>GAF APPS</title>
</head>
<body>
<form method="post" action="branch.php">
<input type="submit" name="submit" value="<?php echo $row["Company"]; ?>">
</form>
</body>
</html>
<?php
}
} else {
echo "0 results";
}
$conn->close();
?>
Here is where I was going to retrieve the value:
<?php
if (isset($_POST['action'])) {
echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>
You don't have an input named "action", therefore the isset() will never happen which is why you did not get an error for it
Having added an else condition for it, would have shown you that instead.
When debuging in PHP I tend the use the shotgun approach and output everything that could be remotely interesting and then narrow it down.
So when looking at parsing form variables use echo var_export($_GET, true) or vardump($_GET).
Not sure if GET or POST? Use _REQUEST which has both in 1 variable.
Use the HTML tag to make it more readable and htmlspecialchars() to convert characters that would normally be invisible because of your browser.
Using those will make it far easier to see what you are doing with your form.
So to answer the above question:
Look at the the mentioned request variables and determine by looking at the HTML and the code if the expected variables should be parsed and send by the browser when the submit button is pressed.
AND
See if the values actually received by PHP will have the expected outcome when handled.
Try to keep those 2 things separate, because what is in your HTML now does not mean it was there when you parsed the form. That's a bit of a bind when developing with PHP/HTML and forms, when you change the code and do not fully reload, but just press Submit on the form:
the code that will parse the current form will be changed, but the contents of the form parsed are the ones that where loaded in your browser and might be out dated.

PHP HTML SQL Passing Parameters to Update Database [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 3 months ago.
I am very new to the subject of PHP and SQL working together and I have been fine so far except for updating a database row on my SQL database. I'm using parts of my lecturers code and doing exercises and my own tasks to modify the webpages and behaviour.
The process of this code is to update an article that I have set up, so I can edit the title or the code then click confirm but when I do this I get my failed return message telling me there is a parameter problem. I have often had trouble passing parameters in other languages and I have been looking and testing this for a few hours that I am hoping to receive some information and guidance on the subject.
All I want to do is update the articletext and articletitle fields.
My EDIT ARTICLE code section:
<?php
$db=createConnection();
// get the first two articles
$sql = "select blogID,articletitle,articletext,blogtime,blogposter,username,userid from blogarticle join registerdemo on blogposter = userid where blogID=?";
$stmt = $db->prepare($sql);
$stmt->bind_param("i",$article);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($articleid,$articletitle,$articletext,$blogtime,$blogposter,$username,$userid);
//build article html
while($stmt->fetch()) {
echo "<article id='a$articleid'>
<h1>$articletitle</h1>
<p>".nl2br($articletext)."</p>
<footer><p>Posted on <time datetime='$blogtime'>$blogtime</time> by <em>$username</em></p></footer>";
// if user is logged in and not suspended add comment button
if($currentuser['userlevel']>2 || ($currentuser['userid']==$userid && $currentuser['userlevel']>1)) {
?> <form method='post' action='applychanges.php'>
<input type="text" name="articletitle" id="articletitle" size="30" required value="<?php echo $articletitle; ?>"/><br />
<textarea name="articletext" id="articletext" cols="60" rows="5"><?php echo $articletext; ?></textarea></br>
<button type="submit">Confirm</button>
</form>
<?php
}
echo "</article>";
}
$stmt->close();
$db->close();
?>
My APPLY CHANGES code:
This is where the parameters fail
<!doctype html>
<html lang="en-gb" dir="ltr">
<head>
</head>
<body>
<?php
include('php/functions.php');
if(isset($_POST['articleid']) && isset($_POST['articletitle']) && isset($_POST['articletext'])) {
$db=createConnection();
$articleid=$_POST['articleid'];
$articletitle=$_POST['articletitle'];
$articletext=$_POST['articletext'];
$updatesql="UPDATE blogarticle SET articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";
$doupdate=$db->prepare($updatesql);
$doupdate->bind_param("ssi",$articletitle,$articletext,$articleid);
$doupdate->execute();
$doupdate->close();
$db->close();
header("location: index.php");
} else {
echo "<p>Some parameters are missing, cannot update database</p>";
print_r($_POST);
}
?>
</body>
</html>
Result:
Some parameters are missing, cannot update database
Array ( [articletitle] => THIS IS A TEST [articletext] => hey )
You are not posting all the parameters with your form. For example, the textarea is missing the name attribute. This will result in not posting this form field your script. Add the following line to your "Apply changes" code. This will print out the parameters you are posting.
print_r($_POST);
Check which parameters are not posted.
You probably want to add some hidden form fields.
The Update query needs to include the data variable names . Query needs to be as follows:
$updatesql="UPDATE blogarticle SET
articletitle='$articletitle', articletext='$articletext' WHERE articleid='$articleid'";

Remove radio buttons where booking already exists

I am trying to make my own booking diary with php, sql and html.
I would like to be able to prevent found booking on my booking form by checking my database to see if a record already exists before allowing my insert statement to execute.
I would ideally like to be able to do a select statement to check if a booking already exists.
IF the TIME AND DATE DOES NOT exist I would like the RADIO BUTTON PRESENT
ELSE
IF the TIME AND DATE DOES I would like the radio button NOT PRESENT .
I have been thinking long and hard but cannot think of a way to do it.
Please could I have some suggestions on how I can overcome my problem?
Thanks
My SQL Table is as follows
TABLE Bookings(
bDate Date,
bTime Time,
bName CHAR(30),
bNumber CHAR(30),
bReg CHAR(30),
bMakeModel CHAR(30)
)
This is what I have so far, but I can't think how to do it, I think I may be going about this the wrong way and perhaps a incremented for loop would be better suited:
<?php
$result = mysqli_query($con,"SELECT * FROM Bookings WHERE bDate = '$_POST[bDate]' ORDER
BY bTime;");
while($row = mysqli_fetch_array($result)){
if $_POST["bDate"] = $row['bDate'] AND $_POST["bTime"] = !$row['bTime']{
<input type="radio" name="bTime" value="08:00:00"> 8:00
}
?>
<input type="radio" name="bTime" value="08:00:00"> 8:00
<input type="radio" name="bTime" value="09:00:00"> 9:00
<input type="radio" name="bTime" value="10:00:00"> 10:00
<input type="radio" name="bTime" value="11:00:00"> 11:00<br>
<input type="radio" name="bTime" value="13:00:00"> 13:00
<input type="radio" name="bTime" value="14:00:00"> 14:00
<input type="radio" name="bTime" value="15:00:00"> 15:00
<input type="radio" name="bTime" value="16:00:00"> 16:00<br>
Until you post some code for a better help, database structure and eventually an exemple of one one or 2 rows. Here are the steps.
For checking part (form) :
If you haven't submitted your form, use AJAX to check in your database.
If you've submitted form, just execute a query on your database.
For SQL part :
A simple count can do the trick (return 0 if no rows found and n if n rows found), but retrieving an ID is better (NULL if no rows found). If you need help on query, describe the table structure, and the fields you are checking.
For the last part (showing or not the label :
In PHP, just need to test your SQL return and implement a condition test on the count value (> 0 or not), or ID (NOT NULL if row found, else NULL).
You can add the radio button (or not) depending of your test result
Tip :
Using ID is better because you can add it in an hidden INPUT tag if you've found a row. If later you decide to update it, it will be possible with this id.
Edit (with your code now) :
In your PHP code you have many errors :
-> your if condition isn't surrounded by the parentheses
-> Logical operators in PHP statement aren't like in SQL : AND (SQL) = && (PHP)
-> Inside your if, the input tag isn't in an echo. input tag is HTML not PHP
Tips :
- Are you sure you have a good connexion ($con) ressource to database?
- In sql string no need to add the final semi-colon ";"
- Always about SQL using the star alias in query run slower than enumerating each field. If one day you need to get a huge resultset, it would be an optimization
Seems nobody answered to your question. Here is a little starting code for you. Don't forget to replace with your database server, user, password and database to connect to mysql :
<?php
$mysqli = new mysqli("host", "user", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>sans titre</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<p>Date : <input type="text" id="bDate" name="bDate" value="" /></p>
<p>Time : <input type="text" id="bTime" name="bTime" value="" /></p>
<input type="submit" value="Send" />
</form>
<hr />
<?php
/* Check if form is submitted */
if (isset($_POST["bDate"])) {
// Need a bDate format = 'YYYY-MM-DD'
if (!preg_match("/^\d{4}\-[0-1][0-9]\-[0-3][0-9]$/", $_POST["bDate"])) {
printf("dDate pattern error for SQL. Waiting YYYY-MM-DD");
exit();
}
/* Execute query */
$query = "SELECT `bDate` , `bTime` , `bName` , `bNumber` , `bReg` , `bMakeModel` FROM `Bookings` WHERE `bDate` = '". $_POST["bDate"] . "' ORDER BY 2";
$result = $mysqli->query($query);
/* Parsing result set */
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
printf ("%s (%s)<br />", $row["bDate"], $row["bTime"]);
if ($_POST["bDate"] == $row["bDate"] && $_POST["bTime"] != $row["bTime"]) {
printf ("<input type=\"radio\" id=\"bTime\" value=\"%s\" /> %s<br />", $row["bTime"], $row["bTime"]);
}
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>
</body>
</html>
You have some checking on mysql connection, POST dDate variable. Also use the free once result set is no more necessary. Hope this help you.

PHP email glitch

This is a school assignment. I don't know all of the fine details of PHP variables and such, but! If I hardcode the id then it sends just like it should. If not, it doesn't at all. Suggestions?
if ((!empty($_subject)) && (!empty($_text))) {
$_dbc = mysqli_connect('localhost', 'user', 'password', 'db') or die ('Error Connecting to MySQL server.');
$_id = $_GET['id'];
$_query = "SELECT * FROM midterm WHERE id = '$_id'";
$_result = mysqli_query($_dbc, $_query) or die ('Error Querying Database.');
while($_row = mysqli_fetch_array($_result)) {
$_to = $_row['email'];
$_firstName = $_row['firstName'];
$_msg = "Dear $_firstName, /n $_text";
mail($_to, $_subject, $_msg, 'From:' . $_from);
echo 'Mail sent to: ' . $_firstName . ' at ' . $_to . '<br />';
}
Addressing $_GET/$_POST problems with a NULL $_GET['id']
<form name="example" action="http://example.com" method="POST"></form>
OR
<form name="example" action="http://example.com" method="GET"></form>
If variables are POSTed from a form, they will be sent through the server and you can access them on the submitted page with $_POST['key']. If variables are sent with GET, they will be appended to the URL in a query string and accessible on the page with $_GET['key'].
When you use the variable $_GET['id'] it is looking in the URL's query string for the key id. If your URL looked like http://example.com/sript.php?id=123 then $_GET['id'] would return 123 not NULL. This can either be accomplished by visiting a specific URL (like shown above) or arriving on the page through a form like below:
<form name="example" action="http://example.com/script.php" method="GET">
<input type="text" name="id" />
<input type="submit" value="Try Me" />
</form>
This form, when submitted, will send the $_GET['id'] variable to script.php using GET.
Addressing other issues with mail not sending
Can you add the following lines of code before your while loop and let me know what they say? This will let me know if your MySQL query is working.
echo "Rows returned: ".mysqli_num_rows($_result)."<br />";
// this line only works on PHP > 5.3.0
echo "Result dump:<br /><pre>".mysqli_fetch_all($_result)."</pre>";
Since mysqli_num_rows() returned 0, that means that your SQL query SELECT * FROM midterm WHERE id = '7' is not returning any results. I can't help any more without looking at the database structure. Double check your code (and compare it to code that works) to try to see what is going wrong. Make sure that there is a row in the table midterm that has an id = 7.

How to edit the user information by admin

I am developing my first simple website using PHP. Now, I am working in the admin page and I want to let him adding, deleting users and editing the personal information of the existed users. I did the adding and deleting. Now, I want to develop editing users. First of all, I want him to choose the user from drop list, then fetch the user information automatically after choosing him from the drop list, and after that editing his information. So how can I do that?
My code:
<?php
ob_start();
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="13524"; // Mysql password
$db_name="sharingi_db"; // Database name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="javascript">
function reload(form){
var val=form.username.options[form.username.options.selectedIndex].value;
self.location='editUser2.php?username=' + val ;
}
</script>
</head>
<body>
<div id="content_main" class="admin_student_height">
<!-- Here starts the first form -->
<form method="get">
<h3>Choose A User</h3> <br />
select name="username" onchange="reload(this.form)">
<option>
<?php
if(isset($_GET['username']))
echo "{$_GET['username']}";
else echo "Select one";
?>
</option>
<?php
if(isset($_GET['username'])){
$exceptcc = $_GET['username'];
$sql = "SELECT username FROM user WHERE user.username NOT IN
('$exceptcc')";
}
else
$sql = "SELECT username FROM user";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "<option value={$row['username']}>{$row['username']}</option>";
}
?>
</select><br /><br />
<h3>User Information</h3> <br />
<?php
$thecc = $_GET['username'];
$sql = "SELECT Firstname FROM user WHERE Username=$thecc";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo "{$row['Firstname']}>{$row['Firstname']}}";
}
?>
<br /><br />
</form> <br />
</div>
</div>
</body>
I've been working on making a web-based ticketing system and ran into this same situation.
I solved the problem like this:
When the page is loaded, determine if they have admin rights or throw them off the page.
Do an SQL Query to get the List of users, to either display in a list or in a drop down box.
Once the User to edit has been selected, Do another Query and load each item into a field;
what I did was use the same form for adding new users but have php build the form and insert the current values for that user into the fields.
When this form is submitted, (and submitter verifed) I have the php script look at the submitted username and use that for the where clause in the sql update statement
If you want me to post up an example of what I did I can do that.
You are only echo'ing the user's information.
Instead, you need to put the information into a form, which will allow for editing.
<?php
if ($_POST['submit']) {
$username = $_POST['username'];
//if you want to update
mysql_query("UPDATE users SET username = '$username', password = '$password'");
//if you want to delete
mysql_query("DELETE FROM users WHERE username = '$username'");
}
?>
<?
//show all users
$user_query = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($user_query)) {
echo $row['username'] . ' ' . $row['first_name'] . ' ' . $row['last_name'];
//and so on.. depending on your table fields
}
?>
<form method="POST">
Username: <input name="name" value="<?echo $row['username'?>"/>
<input type="submit" name="submit"/>
</form>
Load data into your form, and add action to it like "save_user.php
On that page save_user.php get data from $_POST, $_POST["firstName"] where firstName is name of your text field where you have loaded data from db
write query "update tbl_users set FirstName='$firstName', Email='$email" and execute this query, because you are starter this can be enough but remember query written like this can be used for SQL Injection that means you can write SQL query into text field "firstname" and do some stuff, like delete all data or gain passwords, emails etc.
When you get this then use parameters in your MySQL query in order to avoid SQL Injection. But you will manage it.
if you want to fetch the user information automatically from the drop list (without clicking submit button), you need to use AJAX. Here is the link to a very good example on how to use ajax with php and mysql http://www.w3schools.com/php/php_ajax_database.asp

Categories