Set username as author of comment in php/mysql - php

So I'm making a website where registered users are able to make a post, comment on the post as well as reply to the comments and I'm having trouble with displaying the username of whom has commented.
File home.php
<?php
$sql = "SELECT * FROM post LIMIT 3";
$result = $conn->query($sql);
while ($row = mysqli_fetch_assoc($result)){
$id = $row['users_id'];
$sql2 = "SELECT * FROM users WHERE users_username='$id'";
$result2 = $conn->query($sql2);
if($row2 = mysqli_fetch_assoc($result2)){
echo "<div class='comment-box'>";
echo $row['title']."<br>";
echo $row['date_created']."<br>";
echo $row2['users_id']."<br>";
echo $row['content']."<br>";
echo "</p></div>";
if(isset ($_SESSION["username"])){
echo "<button type='button' id='postbtn' onclick='replyFunction()'>Reply</button>";
include 'commentsection.php';
}
}
}
File makeapost.php
<div class="thread">
<form action="<?php echo htmlspecialchars("includes/posts.inc.php");?>"method="post">
<h4>Create a post </h4>
<hr></hr>
<input type="hidden" name="post_id">
<input type="hidden" name="users_id" value="<?php echo ".$_SESSION[username].";?>">
<input type="text" id="thetitle" name="title" placeholder="Title">
<input type="hidden" name="date_created"> <br>
<textarea id="summernote" name="content"></textarea>
<hr></hr>
<button type="submit" id="postbutton" name="submit">Post</button>
</form>
</div>
File posts.inc.php
<?php
include 'dbh.inc.php';
include 'functions.inc.php';
if (isset($_POST["submit"])){
$title = $_POST["title"];
$users_id = $_POST["users_id"];
$content = $_POST["content"];
$date_created = $_POST["date_created"];
$mysqltime = date ('Y-m-d H:i:s');
$sql = "INSERT INTO post (title, users_id, content, date_created) VALUES (?,?,?,?);";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)){
header("location: ../home.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ssss", $title, $users_id, $content, $mysqltime);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
header("location: ../home.php?error=none");
exit();
}
login.inc.php
<?php
if (isset($_POST ["submit"])){
$username = $_POST["username"];
$password = $_POST["password"];
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
if(emptyInputLogin($username, $password) !== false){
header("location: ../home.php?error=emptyinput");
exit();
}
loginUser($conn, $username, $password);
} else {
header("location: ../home.php");
exit();
}
functions.inc.php
function loginUser($conn, $username, $password){
$uidExists = uidExists($conn, $username, $username);
if($uidExists === false){
header("location: ../login.php?error=wrongusername");
exit();
}
$passwordHashed = $uidExists["users_password"];
$checkPwd = password_verify($password, $passwordHashed);
if($checkPwd === false){
header("location: ../login.php?error=wrongpassword");
exit();
} else if ($checkPwd === true){
session_start();
$_SESSION["userid"] = $uidExists["users_id"];
$_SESSION["username"] = $uidExists["users_username"];
$_SESSION["role"] = $uidExists["users_role"];
header("location: ../home.php");
exit();
}
}
Table structure
CREATE TABLE IF NOT EXISTS `post` (
`post_id` int(11) NOT NULL AUTO_INCREMENT,
`users_id` int(11) NOT NULL,
`content` varchar(500) NOT NULL,
`date_created` varchar(500) NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=14;
CREATE TABLE IF NOT EXISTS `users` (
`users_id` int(11) NOT NULL AUTO_INCREMENT,
`users_username` tinytext NOT NULL,
`users_password` longtext NOT NULL,
PRIMARY KEY (`users_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
It may have something to do with the fact that I cannot connect the right user ID from the post table to the users table, since in the users table i have columns such as (users_id(AUTO_INCREMENT), users_username)
but in post table i have (users_id). I am able to make a post and messages are inserted to the database, but theres no users shown.
Any tips on how I can improve this? Right now nothing is being displayed on home.php page, but the posts are still in the database.

Working from the table definitions you posted above (which don't match your PHP code) I created this data:
post table:
post_id
users_id
content
dateCreated
14
6
Here's some content
20 May 2022
15
7
A message
19 May 2022
16
7
Another message
20 May 2022
17
8
I've nothing to say
20 May 2022
18
9
I said everything already.
18 May 2022
Users table
users_id
users_username
users_password
6
Mike
password
7
George
another password
8
Helen
passwd
9
Alice
pword
10
Bob
secret
From this I created this query:
select post_id, content, date_created, u.users_username
from
post
join
(select users_username, users_id from users) u
on post.users_id = u.users_id
order by date_created desc
limit 3;
Which gives this result:
post_id
content
date_created
users_username
14
Here's some content
20 May 2022
Mike
16
Another message
20 May 2022
George
17
I've nothing to say
20 May 2022
Helen
Now you can just loop through the results and create your output without the need for a nested query to retrieve data.
Note:
This is a simple example based on your table structure and some simple data. You can include or exclude some of these columns, change the order, include or exclude more rows.
dateCreated should be a DateTime column, not a varchar column
Passwords should NOT be stored in plain text.
You will need to consider appropriate indexing once these tables start to grow.

Related

How can i use my ID from $_GET in $_POST to insert into table?

So in the start of my file i am get the Id of my product, so i can differ between products and store data correctly. Thats my php:
<?php
if(isset($_GET['dish_did']))
{
//get food id
$dish_did = $_GET['dish_did'];
//get data
$sql = "SELECT * FROM dish WHERE did=$dish_did";
//execute
$res = mysqli_query($link, $sql);
//count rows
$count = mysqli_num_rows($res);
//check whether the data is available or not
if($count==1)
{
//we have data
//get from database
$row = mysqli_fetch_assoc($res);
$nom = $row['nom'];
$description = $row['description'];
$last_rating = $row['last_rating'];
}
else{
//not availible
header("location: error.php");
}
}
else{
header("location: rate.php");
}
?>
After some HTML i have the following POST. I use this to save the data entered by the user in an other table (different table than dish).
<?php
//check whether submit clicked
if(isset($_POST['submit']))
{
//get all details
$dish_id = $_POST['dish.did'];
$review_date = date("Y-m-d h:i:sa"); //Rating Date
$user_review = $_POST['RatingLong'];
//save in database
//Create SQL to save data
$sql2 = "INSERT INTO review SET
user_review = '$user_review',
review_date = '$review_date',
dish_id = '$dish_id'
";
//Execute the Query
$res2 = mysqli_query($link, $sql2);
//check wether query executed successfully or not
if($res2==true)
{
//Query Executed and Review Saved
$_SESSION['review'] = "<div class='success'>Review Successfull.</div>";
// header('location:'.SITEURL);
}
else{
//Failed to save review
$_SESSION['review'] = "<div class='success'>Error.</div>";
// header('location:'.SITEURL.'about.php');
}
}
?>
Without the dish_id i am able to store data, but they arenĀ“t assigned (so useless).
I am not sure how i can link the id correct, to be saved. I have seperate links for every product by id: http://localhost/Project/index.php?dish_did=2 for example.
What i have to change, that user_review and review_date is stored correctly with the same dish_id (table review) as dish_did (table dish).
ADDITIONAL QUESTION:
how can i comment ?
edit:
added rate.php code and database
<?php
$sql = "SELECT * FROM dish WHERE hide ='1'";
$res = mysqli_query($link, $sql);
$count = mysqli_num_rows($res);
if($count>0)
{
echo'<div class="row">';
while($row=mysqli_fetch_assoc($res))
{
$did = $row['did'];
$nom = $row['nom'];
$description = $row['description'];
$last_rating = $row['last_rating'];
?>
<div class="mb-4"></div>
<!-- <div class="row"> -->
<div class="col-md-3">
<div class="thumbnail">
<a href="index.php">
<img src="img/gallery/01.jpg" class="rounded-top">
</a>
<h4 class="text-center my-3"><?php echo $nom; ?></h4>
<p class="text-center"><?php echo $description; ?></p>
Jetzt Bewerten!
<!-- </div> -->
</div>
</div>
<?php
}
}
else{
echo "<div class='error'>Food not available.</div>";
}
?>
Here my database:
create table users
(
uid int primary key AUTO_INCREMENT,
username varchar(25),
password varchar(25),
created_at date,
score int
);
create table dish
(
did int primary key AUTO_INCREMENT,
nom varchar(25),
description varchar(250),
last_rating int,
hide int DEFAULT 0 NOT NULL
);
create table review
(
review_id int primary key AUTO_INCREMENT,
user_id int ,
dish_id int ,
user_rating int ,
user_reveiw varchar(100),
review_date datetime,
foreign key (user_id) references users(uid),
foreign key (dish_id) references dish(did)
);
I found the issue.
It has to be this GET:
$dish_did = $_GET['dish_did'];
And this is the correct sql Statement:
$sql2 = "INSERT INTO review SET
dish_id = '$dish_did',
user_review = '$user_review',
review_date = '$review_date'
";
In summary, I was in trouble because of my designations. I took the wrong ID, it must be $dish_did

Insert command failing [duplicate]

This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
So, I'm having trouble getting data into this table. I have a similar table setup for memberships. If I change the insert into query to membership from join everything works perfectly, but as soon as I change the table to join it stops working. The table seems to be properly setup since it's basically the same as my membership table, but for some reason data will not insert. I can't think of what could be causing my problem so I'm coming to the experts.
Note that this code all works perfectly when going into a different table. Thanks in advance.
if ( isset($_POST['btn-join']) ) {
// clean user inputs to prevent sql injections
$groupID = trim($_POST['groupID']);
$groupID = strip_tags($groupID);
$groupID = htmlspecialchars($groupID);
$teamname = trim($_POST['teamname']);
$teamname = strip_tags($teamname);
$teamname = htmlspecialchars($teamname);
// Query groups to set group name
$query2 = "SELECT groupName FROM groups WHERE groupID='$groupID'";
$result2 = mysqli_query($con,$query2);
$groupquery = mysqli_fetch_array($result2,MYSQLI_ASSOC);
$groupname = $groupquery['groupName'];
// groupID validation
if (empty($groupID)) {
$error = true;
$groupIDError = "Please enter valid Group ID.";
} else {
// check email exist or not
$query3 = "SELECT groupID FROM groups WHERE groupID='$groupID'";
$result3 = mysqli_query($con,$query3);
$count = mysqli_num_rows($result3);
if($count!=1){
$error = true;
$groupIDError = "Provided Group does not exist.";
}
}
// basic teamname validation
if (empty($teamname)) {
$error = true;
$nameError = "Please enter your Team Name.";
} else if (strlen($teamname) < 3) {
$error = true;
$nameError = "Team Name must have at least 3 characters.";
}
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO join(groupID,userID,groupName,teamName) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
if ($membership) {
$errTyp = "success";
$errMSG = "Account successfully updated";
header("Location: dashboard.php");
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
SQL:
CREATE TABLE IF NOT EXISTS `join` (
`jID` int(11) NOT NULL AUTO_INCREMENT,
`groupID` varchar(32) NOT NULL,
`userID` varchar(32) NOT NULL,
`groupName` varchar(35) NOT NULL,
`teamName` varchar(32) NOT NULL,
`joinDate` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`jID`),
UNIQUE KEY `groupID` (`groupID`,`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
join is a reserved word in SQL. To avoid these sorts of issues, use backticks around table and column names:
$query = "INSERT INTO `join`(`groupID`,`userID`,`groupName`,`teamName`) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
As a side note, you should really rewrite this query to use a prepared statement and then bind the variables to it. This is a SQL injection waiting to happen.

PDO/mysql UPDATE query doesn't do anything or display errors

The code that starts on line 49 is doing absolutely nothing. I have tried to display PHP errors, used try and catch with the PDO set attributes etc, which also didn't display an error.
The code worked before in mysqli when I was using the mysql extension to connect but I'm currently in the process of converting the entire application to PDO.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL);
ini_set("display_errors", 1);
if(!isset($_SESSION['eid'])){ header("Location: index.php"); } else {
require('dbconn.php');
$sessionuser = $_SESSION['eid'];
$messageid = $_GET['id'];
try{
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM messages WHERE id = :messageid";
$rs_result1 = $db->prepare($sql);
$rs_result1->bindParam(":messageid", $messageid);
$rs_result1->execute();
$result1 = $rs_result1->fetch(PDO::FETCH_ASSOC);
$senderid = $result1['eidfrom'];
$recid = $result1['eidto'];
$sql1 = "SELECT * FROM employees WHERE eid = :senderid";
$rs_result2 = $db->prepare($sql1);
$rs_result2->bindParam(":senderid", $senderid);
$rs_result2->execute();
$result2 = $rs_result2->fetch(PDO::FETCH_ASSOC);
$sql2 = "SELECT * FROM employees WHERE eid = :recid";
$rs_result3 = $db->prepare($sql2);
$rs_result3->bindParam(":recid", $recid);
$rs_result3->execute();
$result3 = $rs_result3->fetch(PDO::FETCH_ASSOC);
echo "<table>";
echo "<tr><td>To: </td> <td>".$result3['fname']." ".$result3['lname']."</td></tr>";
echo "<tr><td>From: </td> <td>". $result2['fname'] ." ".$result2['lname']."</td></tr>";
echo "<tr><td>Date: </td><td> ". date("l, jS F Y H:i:s", strtotime($result1['date']))."<br /> </td></tr>";
echo "<tr><td>Subject: </td><td>".$result1['subject']."</td></tr>";
echo "<tr><td colspan='2'><img src =\"images/newssplit.gif\"></td></tr>";
echo "<tr><td>Message: </td><td>". $result1['body']." </td></tr>";
echo "</table>";
//line 49 below
if($sessionuser == $senderid) {
$sql3 = "UPDATE `messages` SET `reads`='1' WHERE `id`= :messageid";
$result4 = $db->prepare($sql3);
$result4->bindParam(":messageid", $messageid);
$result4->execute();
} else {
$sql4 = "UPDATE `messages` SET `read`='1' WHERE `id`= :messageid";
$result5 = $db->prepare($sql4);
$result5->bindParam(":messageid", $messageid);
$result5->execute();
}
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
?>
To say the least I am stuck! I've read many a post on here with people having the same issues, and I don't see anything wrong with the code. What am I missing?
EDIT: So far I have checked the schema to ensure that my fields to actually exist, tried using query(), tried using standard variables rather than bindParam placeholders, The variable $messageid definitely has a value at that stage, as I test printed $sql3 after replacing :messageid with $messageid. I have posted some related files and the export of the schema in a zip ZIP. Haven't come to a solution yet, very stuck on this, as the UPDATE query on line 42 of inbox.php works just fine.
EDIT2: Code above updated with safer select queries, schema has been updated with correct data types and indexes cleaned up. But still what's now on Line 49 will not update the value in messages, OR return an error.
EDIT::SOLVED:
The problem wasn't my query, but my if statement. I hadn't fully tested the functionality of the statement and the queries. What I was doing was testing the queries on a message to and from the same user. An eventuality which I hadn't prepared my if statement for (as it happens the statement and queries combined were working all along for normal user 1 to user 2 and vice versa messages). Here's how I got it to work.
if($sessionuser == $senderid && $sessionuser == $recid) {
$result4 = $db->prepare("UPDATE `messages` SET `read_s`='1', `read_`='1' WHERE `id`= :messageid");
$result4->bindParam(":messageid", $messageid);
$result4->execute();
} elseif($sessionuser == $senderid) {
$result5 = $db->prepare("UPDATE `messages` SET `read_s`='1' WHERE `id`= :messageid");
$result5->bindParam(":messageid", $messageid);
$result5->execute();
} else {
$result6 = $db->prepare("UPDATE `messages` SET `read_`='1' WHERE `id`= :messageid");
$result6->bindParam(":messageid", $messageid);
$result6->execute();
}
I changed the column headers from reads and read, to underscored after reading something about reserved words. But then also found it that it actually didn't matter. Thanks for the help everyone!!! The other notes and feedback that I got regarding the schema etc have helped me learn some good practice!! TYTY
based on your provided zip file in comments
Schema
CREATE TABLE IF NOT EXISTS `employees` (
`eid` int(11) NOT NULL AUTO_INCREMENT,
`fname` varchar(50) NOT NULL,
`lname` varchar(50) NOT NULL,
`dob` varchar(50) NOT NULL, -- why not date datatype?
`sdate` varchar(50) NOT NULL, -- why not date datatype?
`address1` text NOT NULL,
`address2` text NOT NULL,
`city` varchar(50) NOT NULL,
`postcode` varchar(50) NOT NULL,
`telephone` varchar(50) NOT NULL,
`mobile` varchar(50) NOT NULL,
`email` text NOT NULL, -- why text?
`password` varchar(50) NOT NULL, -- I can help you solve this next
`depid` int(11) NOT NULL,
`userlevel` int(11) NOT NULL,
`blocked` int(11) NOT NULL,
PRIMARY KEY (`eid`), -- makes sense
UNIQUE KEY `eid` (`eid`) -- why a duplicate key (as PK) ? you already have it covered
) ENGINE=MyISAM;
truncate table employees;
insert employees(fname,lname,dob,sdate,address1,address2,city,postcode,telephone,mobile,email,password,depid,userlevel,blocked) values
('Frank','Smith','dob','sdate','addr1','addr2','c','p','t','m','e','p',1,2,0);
insert employees(fname,lname,dob,sdate,address1,address2,city,postcode,telephone,mobile,email,password,depid,userlevel,blocked) values
('Sally','Jacobs','dob','sdate','addr1','addr2','c','p','t','m','e','p',1,2,0);
CREATE TABLE IF NOT EXISTS `messages` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`eidto` int(11) NOT NULL,
`eidfrom` int(11) NOT NULL,
`read` int(11) NOT NULL,
`reads` int(11) NOT NULL,
`inbox` int(11) NOT NULL,
`sentbox` int(11) NOT NULL,
`subject` text NOT NULL, -- why a text datatype? was it gonna be huge?
`body` text NOT NULL,
`date` varchar(50) NOT NULL, -- why this data type?
PRIMARY KEY (`id`), -- makes sense
UNIQUE KEY `id` (`id`), -- why this dupe?
KEY `id_2` (`id`) -- why?
) ENGINE=MyISAM;
insert messages(eidto,eidfrom,`read`,`reads`,inbox,sentbox,subject,body,`date`) values
(1,2,1,1,1,1,'subject','body','thedatething');
inbox.php
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL);
ini_set("display_errors", 1);
session_start();
//$sessionuser = $_SESSION['eid'];
$sessionuser = 1;
require('dbconn.php');
try {
$db = new PDO($dsn, $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // line added
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // line added
if (isset($_GET["page"])) {
$page = $_GET["page"];
}
else{
$page=1;
};
$start_from = ($page-1) * 10;
$sql = "SELECT * FROM messages WHERE eidto = $sessionuser AND inbox = 1 ORDER BY date DESC LIMIT $start_from, 10";
echo $sql;
$sql2 = "SELECT COUNT(*) FROM messages WHERE eidto = $sessionuser AND inbox = 1 ORDER BY date DESC LIMIT $start_from, 10";
$rs_result = $db->query($sql);
$count = $db->query($sql2)->fetchColumn();
echo "<h3>Inbox</h3>";
echo "<form action='".$PHP_SELF."' method='post'><table><tr><b><td>#</td><td>From</td><td>Subject</td></b></tr>";
while ($row = $rs_result->fetch(PDO::FETCH_ASSOC)) {
$senderid = $row['eidfrom'];
echo "<br>".$senderid;
$messageid = $row['id'];
$result2 = $db->query("SELECT * FROM employees WHERE eid = $senderid");
$row2 = $result2->fetch(PDO::FETCH_ASSOC);
if($row['read'] == 0) {
echo "<tr> <td><input type='checkbox' name='checkbox[]' value='".$row['id']."' id='checkbox[]'></td>";
echo "<td><b>".$row2['fname']." ".$row2['lname']."</b></td>";
echo "<td><b><u><a href='usercp.php?action=messages&f=message&id=".$row['id']."'>".$row['subject']."</a></u></b></td></tr>";
} else {
echo "<tr> <td><input type='checkbox' name='checkbox[]' value='".$row['id']."' id='checkbox[]'></td>";
echo "<td>".$row2['fname']." ".$row2['lname']."</td>";
echo "<td><a href='usercp.php?action=messages&f=message&id=".$row['id']."'>".$row['subject']."</a></td></tr>";
}
};
echo "<tr><td><input type='submit' id='delete' name='delete' value='Delete'></table></form>";
if(isset($_POST['delete'])){
for($i=0;$i<$count;$i++){
$del_id = $_POST['checkbox'][$i];
$sql = "UPDATE `messages` SET `inbox`='0' WHERE `id`='$del_id'";
$result = $db->prepare($sql);
$result->execute();
}
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=usercp.php?action=messages&f=inbox\">";
}
}
// NEED TO MODIFY CODE BELOW SO THAT PREVIOUS LINK DOESN'T LINK TO PAGE 0 WHEN ON PAGE 1
// AND NEXT DISAPPEARS WHEN ON LAST PAGE WITH RECORDS
$sql = "SELECT * FROM messages WHERE eidto = $sessionuser AND inbox = 1";
$sql2 = "SELECT COUNT(*) FROM messages WHERE eidto = $sessionuser AND inbox = 1";
$rs_result = $db->query($sql);
$rows = $db->query($sql2)->fetchColumn();
if($rows > 10) {
$total_pages = ceil($rows / 10);
echo "<a href='usercp.php?action=messages&f=inbox&page=".($page-1)."'>Previous</a>";
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='usercp.php?action=messages&f=inbox&page=".$i."'>".$i."</a> ";
}; echo "<a href='usercp.php?action=messages&f=inbox&page=".($page+1)."'>Next</a>";
} else { }
} catch (mysqli_sql_exception $e) {
throw $e;
}
?>
Check for errors. You had a typo on fetchColumn, something error reporting told me.
Add error reporting to the top of your file(s) which will help find errors.
<?php
mysqli_report(MYSQLI_REPORT_ALL);
error_reporting(E_ALL);
ini_set('display_errors', 1);
The Op has said he is re-writing his code to PDO. As such,
You need to switch to PDO with prepared statements for parameter passing to protect against SQL Injection attacks.
By the way, above line and color poached from Fred's great PHP Answers
Note that I added the try/catch block, and a PDO connection exception attribute to support it.
Here is a checklist of things to cleanup:
Move your GETS toward $_POST due to url caching security concerns, and size limitations.
If you haven't, look into hashing and password_verify. Here is An Example I wrote.
Clean up the datatypes and indexes. Comments are seen in your schema.
Move to safe prepared statements as mentioned above.
So, as for functionality given here, the fake data I inserted appears, and the delete works. I am sure you can take it from here.
Edit
Best practice is to choose column names that are not Reserved Words. The ones in that list with an (R) next to them. The use of back-ticks around all column names in queries is a safeguard against query failure in that regard.
As far as your question of why I back-ticked some and not others. It was 3am, those were showing up as red in my query editor, and I was being lazy in not back-ticking all of them.

TextArea on form only taking a maximum of 50 characters?

When a user tries to enter a review in "textarea" in the form, only 50 characters of review is displayed. I have tried resolving the situation by disabling Jquery form validation changing the field type to tinytext, mediumtext. I am able to enter the full review 200 characters via PHPMyAdmin so I am guessing the problem is with my PHP but I am not able to see anything obvious . If any one could help it would be greatly appreciated.
<label for="review">Your Review</label>
<br/>
<textarea name="review" id="review" rows="15" cols="60"></textarea>
// Check for a review
if (empty($_POST['review'])){
$errors[] = "Please write a review";
} else {
$review = (trim($_POST['review']));
}
if (empty($errors)) { // If no errors were found.
require_once('./includes/mysql_connect.php');
// Make the insert query.
$query = "INSERT INTO films (movie_title, actor, rating, user_id)
Values ('$mt', '$la', '$rating', '$user')";
$result = mysql_query($query);
$id = mysql_insert_id();
$query = "INSERT INTO reviewed (review, movie_id)
values ('$review', '$id')";
$result = mysql_query($query);
<div id="Review_container">
<?php
require_once('./includes/mysql_connect.php');
$review = $_GET['id'];
echo $review;
?>
</div>
Table structure for table `reviewed`
CREATE TABLE IF NOT EXISTS `reviewed` (
`review_id` int(4) NOT NULL AUTO_INCREMENT,
`review` mediumtext NOT NULL,
`movie_id` int(4) NOT NULL,
PRIMARY KEY (`review_id`),
KEY `movie_id` (`movie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
//No value for review
if ($('#review').val() == "") {
$('.error').append("<li>Please enter a review</li>");
error = true;
}
if (error) { // If error found dont submit.
e.preventDefault();
}
}); // End of .submit function: review_a_film.php

retrieve id value from sql database in php which IS NOT last inserted

I have a database that is designed for Football players and so have the table with the following fields:
Person_ID
First_Name
Surname
NicName
Address_Line_1
Contact_Number
Date_of_birth
Postcode
I need to extract the Person_ID for a player without actually entering the ID number as players will not know their individual number and is designed to be used just by the system.
I have the My sql code for selecting a player when certain values are entered:
SELECT `Person_ID` FROM `person` WHERE `First_Name` = 'A Name' and `Surname` = 'Another Name'
This does not however return very well within php when placed into a function. The function I currently have is shown below (php)
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
}
$name and $sname are values which will be entered by the user and they will then be able to transfer to a different team or update their account etc but I need to have the ID selected so that further functions and queries can work fully.
If you want to fetch the ID of the selected player, use the fetch_array function
http://php.net/manual/en/mysqli-result.fetch-array.php
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "Your ID is" . $row['Person_ID'];
}
This of course assumes there is only one result (otherwise we would have to loop) so you might want to check $result->num_rows is equal to 1 and return an error if it isnt (assuming you arent using UNIQUE in your database)

Categories