Hello i have created a databse which store the information sended by the form on my page.
The structure of the database is this :
cid(comment id) uid(value='Anonymous') id(of the page) date message(text of the message)
So when i goes to a particular page of my website, for example http://miostio.com/page.php?id=15
here i can put a comment by a form which send the information that u can see up in my database.
Now on my database are stored the id of the page in which i have putted the comments, but when i try to see the comment in that page by the function : getComments($conn); ,here are displayed all the comments saved in the database and not only the comments with the id of the page.
I want that the comments displayed corresponds to the id of the page, in page with id(15) display the comment of the page with id(15), in page with id(10) display the comment of the page with id(10) exc ...
PHP --> form that send data
echo "<form method='POST' action='".setComments($conn)."'>
<input type='hidden' name='id' value='".$row['id']."'>
<input type='hidden' name='uid' value='Anonymous'>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message'></textarea><br>
<button name='commentSubmit' type='submit' class='comm-btn'>Comment</button>
</form>";
getComments($conn);
other PHP CODE which contain the function called by the form
function setComments($conn) {
if (isset($_POST['commentSubmit'])){
$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$id = $_POST['id'];
$sql = "INSERT INTO comments (uid, date, message, id) VALUES ('$uid', '$date', '$message', '$id')";
$result = $conn->query($sql);
}
}
function getComments ($conn) {
$sql = "SELECT * FROM comments WHERE id = id ORDER BY cid DESC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
You got at least two mistakes (I don't know yet if the rest is ok and working):
1st: Your sql statement doesn't include the variable you're aming for, it just says kinda 'if 1=1'. So change it to:
$sql = "SELECT * FROM comments WHERE id = $id ORDER BY cid DESC"
2nd: You don't have yet $id available in that function.
So include that:
function getComments ($conn) {
$id = intval($_POST['id']); // cast to int for security
$sql = "SELECT * FROM comments WHERE id = $id ORDER BY cid DESC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo "<div class='comment-box'><p>";
echo $row['uid']."<br>";
echo $row['date']."<br>";
echo nl2br($row['message']);
echo "</p></div>";
}
}
"SELECT * FROM comments WHERE id = id ORDER BY cid DESC"
id always === id
You need to give a real id there...
"SELECT * FROM comments WHERE id = $id ORDER BY cid DESC"
Would consider protecting it from sql injection like this:
"SELECT * FROM comments WHERE id = " . (int)$id . "ORDER BY cid DESC"
Related
EDIT: IGNORE ANY SQL INJECTIONS OR VULNERABLE CODE STATEMENTS :D
(School Project).
I wish to create a insert form on my webpage where I can select an artist from a table, including a song from a table and combine them for an insert into a combined foreign key table.
I have managed to do selects and insert with only individual artist and song drop-downs on my web-page, but would wish for combining the two ID's from each table to combine them to a many to many relative table. But when I press the submit button nothing happens, and I'm a beginner and don't know if I'm missing any important bits of actually Posting the information.
For troubleshooting I have tried my code, and tested it. I see if I remove my code theres no problem, so the problem persists on the syntax I believe, as the first dropdown shows, alongside the second dropdown and submit button, but the problem is within the actual processing and SQL query part, where it never goes to the DB..
The problem:
As you can see below I have a the text Song Name appear with a drop-down menu in the bottom left corner including the Artist Name with a submit button. But my problem persists as the select and then insert from the two drop downs into the combined table does not work, it does not actually submit, I want it to post into the DB what can I do. But somethings off? I would appreciate any questions or help, this community is so amazing and wonderful to operate in!
Database
PHP
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl $sql
($conn->error.";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
</form>
<input type="submit" name="mangetilmange" value ="Submit">
change you code to this:
<form method='POST'>
<?php
include('connect_mysql.php');
if(isset($_POST["mangetilmange"])) {
$song_id = $_POST["song_id"];
$artist_id = $_POST["artist_id"];
$sql ="INSERT INTO artist_has_song (song_id, artist_id) VALUES
('$song_id', '$artist_id')";
if($conn->query($sql)) {
echo "Completed";
} else {
echo "Blablalbablablablablablablabl";
}
}
?>
Song Name
<?php
$sql = "SELECT * FROM song";
$resultat = $conn->query($sql);
echo "<select name='song_id'>";
while ($rad = $resultat->fetch_assoc()) {
$song_id = $rad["song_id"];
$songname = $rad["songname"];
echo "<option value='$song_id'>$songname</option>";
}
echo "</select>";
?>
Artist Name
<?php
$sql = "SELECT * FROM artist";
$resultat = $conn->query($sql);
echo "<select name='artist_id'>";
while ($rad = $resultat->fetch_assoc()) {
$artist_id = $rad["artist_id"];
$artistname = $rad["artistname"];
echo "<option value='$artist_id'>$artistname</option>";
}
echo "</select>";
?>
<input type="submit" name="mangetilmange" value ="Submit">
</form>
I have rows showing products and their stockings.
I can pull out records from the database but somehow I am stuck at the editing part. When I click on edit I don't know how to pass the id so I can use the id to select what is needed to be selected in the table.
I have something like stock.php which shows all item_name and stock
<?php
$sql = "SELECT * FROM inventory";
$result = mysqli_query($mysqli,$sql);
//make sure database queries
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
if ($result->num_rows > 0) {
echo "<table><tr><td>Name</td>
<td>Stock</td>
</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
echo "<tr>
<td>".$row["item_name"]."</td>
<td>".$row["stock"]."</td>
<td>
<form action='edit.php' method='POST'>
<input type='hidden' name='$id' value='$id'/>
<input type='submit' name='edit' value='edit' />
</form>
</td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
?>
in my edit.php I have something like this which is giving me error because the $id is not passed
include_once "init.php";
if ($_SERVER['REQUEST_METHOD']=='POST') {
// query the table by matching up the int id
$sql = "SELECT * FROM inventory WHERE id = '$id'";
}
I want to pull out the data again in a new page and then having input box again to let users update stock # or even the product name and others if necessary.
There is an error in your input declaration. HTML items can't have names that start with special characters (like the $). You should be setting the variable-based names this way:
<input type='hidden' name='".$id."' value='".$id."'/>
Also in your edit.php, your SQL statement has a bug.
$sql = "SELECT * FROM inventory WHERE id = '$id'";
should be:
$sql = "SELECT * FROM inventory WHERE id = ".intval($id);
You need to do the following updates:
stock.php
<input type='hidden' name='id' value='$id'/>
edit.php
$sql = "SELECT * FROM inventory WHERE id = '".$_POST["id"]."'";
you are passing the current id value as the post var name, the var's name should be "id"
I am currently in the middle of constructing a website for my own personal education to better myselft at work and have encountered a problem.
I am wanting to have the ability to update records located on my database via a form.
This is what I have got so far, am i on the right lines?
Thanks in advance
Edit Book Form
<?php
include 'database_conn.php'; // make db connection
//Get the bookISBN from the request stream
$bookISBN = $_REQUEST['bookISBN'];
//use that code in an sql statement to retrieve the details for the Book
$sql = "SELECT bookISBN bookTitle bookYear bookPrice FROM nbc_book where bookISBN = $bookISBN" ;
//Execute the query
$rsAdmin = mysqli_query($conn, $sql) or die(mysqli_error($conn));
//get the records from the result set into variables
$adminBook = mysqli_fetch_array($rsAdmin);
$bookISBN = $adminBook['bookISBN'];
$bookTitle= $adminBook['bookTitle'];
$bookYear= $adminBook['bookYear'];
$bookPrice= $adminBook['bookPrice'];
//Display those variables in a form
?>
<form action ='editBook.php' method = 'GET'>
<?php
echo "StudentID: $bookISBN<br />";
echo "<input type = 'hidden' name = 'bookISBN' value ='$bookISBN' />";
echo "<input type ='text' name'$bookTitle' value='$bookTitle'>";
echo "Book Title:<input type ='text' name'bookTitle' value='$bookTitle'><br />";
echo "Book Year:<input type ='text' name'bookYear' value='$bookYear'><br />";
echo "Book Price:<input type ='text' name'bookPrice' value='$bookPrice'><br />";
echo "<input type ='submit' value='Save'/>";
mysqli_close($conn);
?>
</form>
Edit Book Process
<?php
// make db connection
include 'database_conn.php';
//Get the bookISBN from the request stream
$bookISBN = $_REQUEST['bookISBN'];
$bookTitle = $_REQUEST['bookTitle'];
$bookYear = $_REQUEST['bookYear'];
$bookPrice = $_REQUEST['bookPrice'];
//construct an SQL Statement
$sql = "UPDATE nbc_books set bookTitle ='$bookTitle', bookYear ='$bookYear, $bookPrice where bookISBN = '$bookISBN'";
//execute the SQL statment
$rsBookUpdate = mysql_query ($bookUpdateSQL);
if ($rsBookUpdate === false) {
echo 'Updating Book failed $bookISBN, $bookTitle failed: ' . mysql_error ();
}
?>
<!--draw link taking them back to books list-->
Go back to all book records
you missed quote (`): please check with your database field and query.
$sql = "UPDATE nbc_books set bookTitle ='$bookTitle', bookYear ='$bookYear', bookPrice = '$bookPrice' where bookISBN = '$bookISBN'";
I am newbie in PHP and with this less knowledge of PHP i developed a form to update the rows of MySQL table. But the problem is that if i edit one row in index.php file and submit it then that row value comes to all rows of the table.
I want to change the edited inputs and the rest inputs should be unchanged.
Please note that first row budget value will be added when second row budget value and will be inserted in total input and will save to database
This is how it looks
this is the index.php file
<?php
$con=mysqli_connect("127.0.0.1","root","","ji001");
$result = mysqli_query($con,"SELECT * FROM finance")
or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result))
{ $Budget = $row['Budget'];
$Availed_in_Regions = $row['Availed_in_Regions'];
echo "<form style='width:780px' action='update2.php' method='post' class='form-group'>
id<input type='text' name='Budget' value='".$row['ID']."'>
Budget<input type='text' name='Budget' value='".$row['Budget']."'>
Availed in Regions <input type='text' name='Availed_in_Regions' value='".$row['Availed_in_Regions']."'>
<input type='Submit'>
</form>";
}
?>
This is the update2.php file
<?php
mysql_connect('127.0.0.1', 'root', '') or die(mysql_error());
mysql_select_db("ji001") or die(mysql_error());
$ud_Budget = mysql_real_escape_string($_POST["Budget"]);
$ud_Availed_in_Regions = mysql_real_escape_string($_POST["Availed_in_Regions"]);
$query="UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions'";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>Record Updated<p>";
}else{
echo "<p>Not Updated<p>";
}
?>
Firstly, your form having typo id and name having same name for the name attribute i.e. name='Budget'
index.php
echo "<form style='width:780px' action='update2.php' method='post' class='form-group'>";
while($row = mysqli_fetch_array($result))
{
$Budget = $row['Budget'];
$Availed_in_Regions = $row['Availed_in_Regions'];
echo "id<input type='text' name='id[]' value='".$row['ID']."'>
Budget<input type='text' name='Budget[]' value='".$row['Budget']."'>
Availed in Regions <input type='text' name='Availed_in_Regions[]' value='".$row['Availed_in_Regions']."'>";
}
echo "<input type='Submit' value='Submit'></form>";
and you need to change your update query from
update2.php
$ud_id = $_POST["id"];
$ud_Budget = array_map('mysql_real_escape_string', $_POST['Budget']);
$ud_Availed_in_Regions = array_map('mysql_real_escape_string',$_POST["Availed_in_Regions"]);
foreach($ud_id as $key => $value){
$query = "UPDATE finance SET Budget = '$ud_Budget[$key]', Availed_in_Regions = '$ud_Availed_in_Regions[$key]' where ID = $value";
mysql_query($query)or die(mysql_error());
if(mysql_affected_rows()>=1){
echo "<p>Record Updated<p>";
}else{
echo "<p>Not Updated<p>";
}
}
Here I have added where condition which is required to identify which row you need to update and
NOTICE : You were mixing two API within index.php you were using mysqli_ and within update2.php its mysql
You are not using a where clause in the $query query.
it should be something like this
$query="UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions' WHERE id = '$id'";
You should also pass this id in the form, also change the name of the input field containing the id...
Because you actually SELECT every row in your table.
UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions';
There is no WHERE clause (link) in your query you have to use it if you wanna update a row in your table.
Pass $id to your update2.php and use this query instead:
UPDATE finance SET Budget = '$ud_Budget', Availed_in_Regions = '$ud_Availed_in_Regions' WHERE id = '$id';
I have a problem regarding my correct script for query..
I created a form in page1.php where the user have to input the fname, mname, and lname.
page1.php
<form action = "page2.php" method="post" target="<?php $_SERVER['PHP_SELF']?>">
First Name:<input type="text" name="fname"/>
Middle Name:<input type="text" name="mname"/>
Last Name:<input class = "type="text" name="lname"/>
<input type="submit" name="submit" value="NEXT" />
</form>
The entries are sent to page2.php to be inserted into the database. After successful process. I placed a condition after a successful insertion of the values, it automatically goes to page3.php.
page2.php
<?php
include('config.php');
if(isset($_POST['submit']))
{
$fname = ucwords(strtolower($_POST['fname']));
$lname = ucwords(strtolower($_POST['lname']));
$mname = ucwords(strtolower($_POST['mname']));
$submit=$_POST['submit'];
if(empty($fname) || empty($lname) || empty($mname))
{
echo '<b>Please fill out the form completely.</b>';
}
else
{
$dup = mysql_query("SELECT *
FROM
tbl
WHERE
fname = '$fname'
AND
lname = '$lname'
AND
mname = '$mname'
");
if(mysql_num_rows($dup) >0)
{
echo "<br/>";
echo '<b>Already Registered.</b>';
echo "<br/>";
}
else
{
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname) VALUES('$fname','$lname','$mname')");
if($sql)
{
echo "<br/>";
echo "You have successfully added your new name!";
echo "<br/>";
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
}
else
{
echo "Error Registration";
header("Location: index.php");
}
}
}
}
?>
The values will also be carried over by the:
header("Location: page3.php?fname= $fname&mname= $mname &lname= $lname");
which is placed right after the:
$sql = mysql_query("INSERT INTO tbl(fname,lname,mname)VALUES('$fname','$lname','$mname')");
Then goes to next page.
In page3.php, in order to verify that I still have the values I used:
echo '<pre>' . print_r($_GET,true) . '</pre>';
And I still have them.
Now, in page3.php I want to call the auto_incremented ID that was created after the successful insertion of the values from page2.php.
<?php
echo '<pre>' . print_r($_GET,true) . '</pre>';
include('config.php');
$fname = $_GET['fname'];
$mname = $_GET['mname'];
$lname = $_GET['lname'];
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
?>
Now, the problem is that their no results coming out from my query. When I try this is script:
$sql = mysql_query("SELECT * FROM tbl");
I have results showing up.
What I want to do is this, I want the conditions to be fulfilled altogether namely the fname, mname, lname. The 3 fields must be satisfied so that I can get the specified ID from the table which has those fields specifically. Its like you have the query your fullname and get the ID for you. You should insert all 3 fields in order to get the exact ID for that given name.
My problem probably lies here:
$sql = mysql_query("SELECT * FROM tbl WHERE fname = '$fname' AND mname = '$mname' AND lname = '$lname'");
while ($row = mysql_fetch_array($sql))
{
echo $row['id'];
}
It's like you to have John Rogers Smith then find out your ID from the database.
Can you help me? I dont understand why it's not working.
Tnx guys in advance.
Please check every stap you do, because the form already has an error
Last Name:<input class = "type="text" name="lname"/>
needs to be
Last Name:<input class="" type="text" name="lname"/>
and the way you do the querys is not secure, its easy to do sql injection.
Also i would suggest you to use sprintf(), example:
$s_query = sprintf("SELECT * FROM `x` WHERE `x`.`x_name` = '%s'", $x_name);
And you should go for mysqli instead of mysql.
Next time always print out every stap, use print_r() to print arrays like $_GET and $_POST
may i ask to all it may work without give error or warning
echo "Error Registration";
header("Location: index.php");