I currently followed a tutorial for a public user chat where it uses Msg_ID, Sender, Message. Sender being the name. I currently have a friend table where:
ID, my_id, friend_id.
But am unsure how to alter the chat so it's only sent to the recipient vice versa. And I have changed the chat table to the following: Msg_id, Author_id, Recipient_id, Message.
The current query for the chat is:
<?php
function get_msg() {
$query = "SELECT `Author_ID`, `Message` FROM `pdo_ret`.`chat` ORDER BY `Msg_ID` ASC";
$run = mysql_query($query);
$messages = array();
while($message = mysql_fetch_assoc($run)) {
$messages[] = array('Author_ID'=>$message['Author_ID'],
'message'=>$message['Message']);
}
return $messages;
}
function send_msg($Author_ID, $message) {
if(!empty($Author_ID) && !empty($message)) {
$Author_ID = mysql_real_escape_string($Author_ID);
$message = mysql_real_escape_string($message);
$query = "INSERT INTO `pdo_ret`.`chat` (Msg_ID, Author_ID, Message) VALUES (null, '{$Author_ID}', '$message')";
if($run = mysql_query($query)) {
return true;
} else {
return false;
}
} else {
return false;
}
}
?>
While the form for the chat is:
<form action="#" method="post" onsubmit="return InsertDefaultValues()" id="form_input">
<input hidden type="text" name="Author_ID" id="Author_ID"/>
<input hidden type="text" name="friend_id" id="friend_id"/>
<input type="text" id="message" cols="5" rows="4"></textarea>
<input type="submit" name="send" onsubmit="return InsertDefaultValues()" id="send" value="Send Message"/>
</form>
Here is my script for the session which I'm trying to use to define the user that is logged in.
<?php
session_start();
if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"]));
?>
The following changes should be done to the queries:
Retrieve only your messages:
$query = "SELECT `Author_ID`, `Message` FROM `pdo_ret`.`chat` WHERE Recipient_id = '$Recipient_id' ORDER BY `Msg_ID` ASC";
Specify the recipent:
$query = "INSERT INTO `pdo_ret`.`chat` (Msg_ID, Author_ID, Recipient_id, Message) VALUES (null, '{$Author_ID}', '$Recipient_id', '$message')";
<?php
session_start();
if(!isset($_SESSION["user"]) or !is_array($_SESSION["user"]) or empty($_SESSION["user"]));
?>
Related
i want to make TOEFL test. when user want to start the test, first user must input email. So, when user click start, user have an id. I want take id from table 'id' and save it in session. so when i want to take score from 'listening', 'structure' and 'reading' table, i used that id.
but the problem is: when i do the test, listening, reading and structure score will be '0'. but i sure i has answered the questions correctly. Maybe it because id not save in session correctly. please help meeee
index.php
<form method="POST" action="add_id.php">
<input type="text" name="email" placeholder="Email">
<input name="btn" type="submit" value="Start"/>
</form>
add_id.php
<?php
include "connection.php";
$email = $_POST['email'];
$query = "INSERT INTO id(email) VALUES ('$email')";
if(mysql_query($query)){
$q = "SELECT * FROM id";
$ex=mysql_query($q);
$id = $ex['id'];
session_start();
$_SESSION['id'] = $id;
header("location:test_structure.php");
}
else {
echo mysql_error();
}
?>
calculate.php
<?
include "connection.php";
$id =$_SESSION['id'];
$query ="SELECT * FROM Reading WHERE Reading.id='$id'";
$ex=mysql_query($query);
$data=mysql_fetch_array($ex);
$right_structure = $data['rightanswer_read'];
$Reading = $data['score_read'];
$query ="SELECT * FROM Structure WHERE Structure.id='$id'";
$ex=mysql_query($query);
$data=mysql_fetch_array($ex);
$right_structure = $data['rightanswer_struct'];
$Structure = $data['score_struct'];
$q ="SELECT * FROM Listening WHERE Listening.id='$id'";
$e=mysql_query($q);
$d=mysql_fetch_array($e);
$right_listening = $d['rightanswer_list'];
$Listening = $d['score_list'];
$final_score = (($Listening + $Structure + $Reading)/3) * 10;
$NA = "INSERT INTO final_score VALUES ('$email', '$final_score', '$Listening', '$Structure', '$Reading', '$right_listening', '$right_structure', '$right_reading')";
if(mysql_query($NA)){
header("location:index.php");
}else {
echo mysql_error();
}
}
?>
this is id table structure:
CREATE TABLE IF NOT EXISTS `id` (
`id` int(100) NOT NULL,
`email` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Change your add_id.php file like this,
<?php
session_start();
include "connection.php";
$email = $_POST['email'];
$query = "INSERT INTO id(email) VALUES ('$email')";
if(mysql_query($query)){
$id = mysql_insert_id();
$_SESSION['id'] = $id;
header("location:test_structure.php");
}
else {
echo mysql_error();
}
?>
Also read about function mysql_insert_id() at http://php.net/manual/en/function.mysql-insert-id.php
I'm building a website where users should be able to input music artists and albums into a database. I have tables artists and albums in the musique database.
I'm trying to select artistId from artists and associate it with whatever album the user is trying to input. The artistId keeps coming back as 0, though. I think something is wrong with my SELECT statement, but I'm not totally sure.
Does anyone see a reason why this is happening?
inputalbum.php:
<?php
include "session.php";
include "db.php";
SessionClient::checkIfLoggedIn();
// Get list of artists to suggest
$conn = DB::connect();
$results = $conn->query("SELECT artistName FROM artists");
$artists = [];
while ($row = $results->fetch_assoc()) {
$artists[] = $row;
}
?>
<?php include "header.php"; ?>
<div class="container">
<h1>INSERT ALBUM</h1>
<form class="form" enctype="multipart/form-data" action="albumredir.php" method="POST">
<fieldset>
<label for ="artistName">Artist</label>
<input type="text" name="artistName">
<br>
<!-- <div>
Artists already in the database: <span>?</span>
</div> -->
<script>
// Transfer php array to js to use on the browser
var artists = <?php echo json_encode($artists) ?>;
// Grab the artist input field
var artistInput = document.querySelector('input[name="artists"]');
// Set an event for when they change to suggest artists
artistInput.oninput = function () {
var currentValue = artistInput.value;
var suggestedArtists = [];
artists.forEach(function (artist) {
var enteredArtists = currentValue.split(',');
if (artist.label.match(enteredTags[enteredArtists.length - 1].trim())) {
suggestedArtists.push(artist);
}
});
var suggestionString = suggestedArtists.map(t => t.label).join(',');
document.querySelector('div span').innerHTML = suggestionString;
}
</script>
<label for="albumName">Album Name:</label>
<input type="text" name="albumName" placeholder="Album One">
<br>
<label for="relDate">Release Date:</label>
<input type="date" name="relDate">
<br>
</fieldset>
<fieldset>
<input type="submit" name="submit" value="Submit">
</fieldset>
</form>
</div>
albumredir.php:
<?php
session_start();
$artistName = $_POST['artistName'];
$albumName = $_POST['albumName'];
$relDate = $_POST['relDate'];
$submit = $_POST['submit'];
include "db.php";
$conn = DB::connect();
$artistId = $conn->query("SELECT artistId FROM artists WHERE artistName = $artistName");
$stmt = $conn->prepare("INSERT INTO albums (artistId, userId, albumName, relDate) VALUES (?, ?, ?, ?)");
$stmt->bind_param(
"iiss",
$artistId,
$_SESSION['currentUser']['userId'],
$_POST['albumName'],
$_POST['relDate']
);
if(isset($_SESSION['currentUser']['userId']))
{
$currentUser = $_SESSION['currentUser']['userId'];
}
else
{
$currentUser = NULL;
}
if(isset($_POST['albumName']))
{
$albumName = $_POST['albumName'];
}
else
{
$albumName = NULL;
}
if(isset($_POST['relDate']))
{
$relDate = $_POST['relDate'];
}
else {
$relDate = NULL;
}
$stmt->execute();
// Close the connection
$conn->close();
// header('Location: index.php');
?>
$artistId = $conn->query is returning a result set, so you can't bind to it directly later when you try:
$stmt->bind_param(
"iiss",
$artistId,
you will need to fetch the artistId from the result set first.
In this example, I change the name of the result set from $artistId to $result for clarity.
$result = $conn->query("SELECT artistId FROM artists WHERE artistName = $artistName");
// get row from result
$row = $result->fetch_assoc();
// get artistID from row
$artistId = $row["artistId"];
$stmt = $conn->prepare("INSERT INTO albums (artistId, userId, albumName, relDate) VALUES (?, ?, ?, ?)");
$stmt->bind_param(
"iiss",
$artistId,
$_SESSION['currentUser']['userId'],
$_POST['albumName'],
$_POST['relDate']
);
I have this page of html
<html>
<body>
<form action="new_group.php" method="post">
<div>
<label for="group_name">Group Name: </label>
<input type="text" name="group_name" id="group_name" />
</div>
<div>
<label for="invites">Invite...</label>
<input type="text" name="invites" id="invites" />
</div>
<div>
<label for="description">Description: </label>
<textarea name="description" id="description"></textarea>
</div>
<div>
<input type="submit" value="Create" />
</div>
</form>
</body>
</html>
Which then has this PHP:
<?php
include "function_inc.php";
if(isset($_POST['group_name'], $_POST['description'], $_POST['invites'])){
$invites = explode(',', $_POST['invites']);
$user_id = $_SESSION['user_id']; //avoids issues with quotations (either invalid quotation for referring to PHP variable or repeated double quotes)
$result = mysqli_query($link, "SELECT `username` FROM `users` WHERE `user_id` = '$user_id'");
foreach($result as $resul){
foreach($resul as $resu){
$logged_in_username = $resu;
}}
if(in_array($logged_in_username, $invites)){
}else{
$invites[] = $logged_in_username;
}
foreach($invites as $invite) {
$invite = trim($invite);
echo $invite . '<br />';
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
if(mysqli_num_rows($idres) == 0) {
exit("1 or more of the users that you entered do(es) not exist!");
}
}
create_group($_POST['group_name'], $_POST['description'], $invites);
}
?>
and this is the create_group function:
function create_group($name, $description, $invites){
global $link;
$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");
$descriptions = mysqli_query($link, "SELECT `group_description` FROM `groups` WHERE `group_description` = '$description'");
if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0) {
mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
} else {
echo 'Group with that name/description already exists.';
}
$result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");
foreach($result as $resul) {
foreach($resul as $resu) {
$group_id = $resu;
}
}
foreach($invites as $invite) {
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
foreach($idres as $idarr) {
foreach($idarr as $id) {
mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
}
}
}
echo 'Group created!';
}
What I am confused about is the following: if I create a group (for testing purposes) and include my (the current user logged on's) name, and have commas but no spaces in between, everything works fine. However, if I do the exact same thing, however I have spaces, only the first name in the array enters group_members. As you can see, there is a trim statement.
I have no idea why this is. Any help would be much appreciated as I am a beginner at PHP.
Thank you in advance
In the code:
foreach ($invites as $invite) {
$invite = trim($invite);
...
}
The variable $invite is separate from the array element. Assigning to that variable does not modify the contents of the array. You can fix this by using a reference:
foreach ($invites as &$invite) {
$invite = trim($invite);
...
}
The & prefix makes $invite a reference variable, i.e. an alias for the array element. Now, assigning to the variable updates the array element that it refers to.
first time I've used this site .. I've had a good look around but I cant seem to find the answer to my question. It's been answered in other ways but not for what I want I think..
Image of the database table so it's easy to see: http://puu.sh/6BtmZ.png
So basically I've got a friends.php page that has an input field and submit button, you put a username in and press submit and I want it to send a request to that user; I've got that to work, the user can accept but it only places the "friend" into him. As in FRIENDA is friends with FRIENDB but on FRIENDB's page he isn't friends with FRIENDA .. I hope this makes sense.
I just basically want it so, you send a request and the person accepts it and BOTH parties can see each other as friends.
<?php
include 'core/init.php';
// check
protect_page();
include 'includes/templates/header.php';
$user_id = $user_data['user_id'];
if (empty($_POST) === false) {
$required_fields = array('username');
foreach($_POST as $key=>$value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'You need to enter a username to send a request!';
break 1;
}
}
if (empty($errors) === true) {
if (user_exists($_POST['username']) === false) {
$errors[] = 'Sorry, the username \'' . htmlentities($_POST['username']) . '\' doesn\'t exist.';
}
}
}
if (isset($_GET['success']) && empty($_GET['success'])) {
echo 'Friend request sent!';
} else {
if (empty($_POST) === false && empty($errors) === true) {
// add friend
$username = $_POST['username'];
$get_userid = mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'");
$row = mysql_fetch_array($get_userid);
$username_id = $row[user_id];
$user_id = $user_data['user_id'];
mysql_query("INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')");
//redirect
header('location: friends.php?success');
//exit
exit();
} else if (empty($errors) === false) {
// output errors
echo output_errors($errors);
}
}
?>
<h1>Friends</h1>
<p>
<h2>Send a friend request:</h2>
<form id="friend_request" action="" method="POST">
<ul>
<li>Username: <input type="text" name="username"><input id="friend_request" type="submit"></li>
</ul>
</form>
</p>
<p>
<h2>Pending requests:</h2>
<?php
if(isset($_POST['decline'])){
$decline_id = $_POST['decline_friend_id'];
$decline_query = "DELETE FROM `users_friends` WHERE `id` = $decline_id";
$accept_result = mysql_query($decline_query);
}
if(isset($_POST['accept'])){
$accept_id = $_POST['accept_friend_id'];
$accept_query = "UPDATE `users_friends` SET `request_pending` = 0 WHERE `id` = $accept_id";
$accept_result = mysql_query($accept_query);
}
$result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 1");
while($requests_row = mysql_fetch_array($result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$requests_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$request_from = $get_username_row[username];
echo 'Request from: ' . $request_from . '<form id="decline" action="" method="POST">
<input type="hidden" name="decline_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Decline" name="decline">
</form>
<form id="accept" action="" method="POST">
<input type="hidden" name="accept_friend_id" value="' . $requests_row['id'] . '">
<input type="submit" value="Accept" name="accept">
</form>';
echo '<br />';
}
?>
</p>
<h2>Your friends:</h2>
<?php
$friends_result = mysql_query("SELECT * FROM `users_friends` WHERE `friends_with` = '$user_id' AND `request_pending` = 0");
while($friends_row = mysql_fetch_array($friends_result)) {
$get_username = mysql_query("SELECT `username` FROM `users` WHERE `user_id` = '$friends_row[user_id]'");
$get_username_row = mysql_fetch_array($get_username);
$friend = $get_username_row[username];
echo $friend . '<br />';
}
?>
</p>
<?php include 'includes/templates/footer.php'; ?>
Hopefully someone might be able to help? Thanks in advance!
What you probably want to do is insert both directions in the friends relationship once both friends have confirmed. So instead of doing this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id')
You would do this:
INSERT INTO `users_friends` (user_id, friends_with) VALUES ('$user_id', '$username_id'),('$username_id','$user_id')
This would allow you to do the friend lookup in either direction.
What is unclear to me however is how you store pending friend requests in your database. So what you may ultimately need to do is to insert those relations in the DB and then simply update those DB records to change the value of an "accepted" flag once the friendship has confirmed.
If the structure of "users_friends" table looks like this:
me friends_with request_pending
to get the result (= if the user is your friend):
"SELECT * FROM `users_friends` WHERE (`friends_with` = '$user_id' AND `me`= `$me`) OR (`friends_with` = '$me' AND `me`= `$user_id `) AND `request_pending` = 0"
You check if the user is in friends_with where YOU are in me.. or if the user is in me and you're in friends_with
Here is my PHP code:
// Collect data from URL
$mid = $_GET['m'];
if (isset($_POST['submit']))
{
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = '". $mid ."', date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
}
The data gets entered in the database correctly except the $mid
But if in my HTML I put this :
<?php print $mid;?>
Then i can see the print of the ID number ... so I know my variable $mid has the proper value.... I don't know why it not getting inserted in the DB.
I also tried this SQL
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = "$mid", date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
Same thing... everything works except the value of $mid doesn't go in the DB.
My field in the DB is set to Int(11) and there is no mistake in the column name.. i checked 5 times... Don'T know what's wrong.. thx
ENTIRE CODE HERE :
<?
ob_start();
include 'datalogin.php';
//checks cookies to make sure they are logged in
if(isset($_COOKIE["user"]))
{
$username = $_COOKIE["user"];
$pass = $_COOKIE["password"];
$check = mysql_query("SELECT * FROM members WHERE email = '$username'")or die(mysql_error());
$loginuser = false;
while($info = mysql_fetch_array( $check ))
{
if(! $loginuser)
{ $loginuser = $info; }
//if the cookie is present but has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{
header("Location: login.php");
exit();
}
else //if the cookie is present and doesn'T have the wrong password they are shown the admin area
{
include 'header.php';
}
}
}
else //if there is no cookie present
{
header("Location: login.php");
exit();
}
// Collects data from images table
$mid = $_GET['m'];
$data = mysql_query("SELECT images.image_id, images.members_id, images.image_url, members.members_id, members.name, members.age
FROM members
LEFT JOIN images
ON members.members_id=images.members_id WHERE members.members_id ='". $mid ."' ")
or die(mysql_error());
$data2 = mysql_fetch_array( $data );
if (isset($_POST['submit']))
{
$insert = "insert into booking SET from_id = '".$loginuser['members_id']."', to_id = '$mid', date = '".$_POST['date']."'";
$add_member = mysql_query($insert) or die(mysql_error());
header('Location: index.php');
exit();
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" >
<table cellspacing='0' id="booking" align="center" width="680">
<tr>
<td>Date:</td>
<td><input name="date" type="text" size="10" maxlength="10" class="form-field" /> </td>
</tr>
<tr>
<td> </td>
<td><input class="submit-button" type="submit" name="submit" value="SEND REQUEST" /></td>
</tr>
</table>
</form>
<br />
HERE IS THE TABLE STRUCTURE
CREATE TABLE IF NOT EXISTS `booking` (
`booking_id` int(11) NOT NULL AUTO_INCREMENT,
`from_id` int(11) NOT NULL,
`to_id` int(11) NOT NULL,
`date` varchar(10) NOT NULL,
PRIMARY KEY (`booking_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ;
Try in this way
if (isset($_POST['submit']))
{
$mid = $_GET['m'];
$insert = "insert into table SET from_id = '".$loginuser['members_id']."', to_id = '". $mid ."', date = '".$_POST['date']."' ";
$add_member = mysql_query($insert);
}