Can't select id from different table in MySQL database - 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']
);

Related

My function doesn't post in the database

So I tried coding a function that allows the user to post a mood, chosen by a slider. I succeeded in connecting the color with an ID, then I tried making a post function. However Nothing happens.
this is where i call the functions.
if (isset($_POST['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}
these are the two functions.
public function getMood($moodColor){
$conn = db::getInstance();
$statementMood = $conn->prepare("SELECT * FROM moods WHERE color = :cMood");
$statementMood->bindParam(":cMood", $moodColor);
$statementMood->execute();
return $statementMood;
}
public function postMood(){
$conn = db::getInstance();
$statementPost = $conn->prepare("INSERT INTO postsmoodi (userID, moodID) VALUES (:userID, :moodID)");
$statementPost ->bindValue(':userID', $this->userID);
$statementPost->bindValue(':moodID', $this->moodID);
return $statementPost->execute();
}
this is the form where the button to post is.
<form class="input" action="mood.php" method="get">
<input id="hiddenValue" type="hidden" class="data" name="mood" value="">
<button class="moodReady" type="submit" name="ready">Ready</button>
</form>
Use $_GET instead of $_POST, as your form uses method="get"
if (isset($_GET['ready'])) {
$mood = new Post();
$moodColor = $_POST['mood'];
$statementMood = $mood->getMood($moodColor); //connects the color with an ID
while ($row = $statementMood->fetch(PDO::FETCH_ASSOC)) {
$moodID = $row['moodID'];
}
$moodID = $_GET['moodID'];
$userID = $currentUser['userID'];
$statementPost = $mood->postMood(); //put the emotion in the database.
//header('location: home.php');
}

phpmyadmin not using DEFAULT value when input is left empty

I have this problem where if I leave my input for 'Title' blank, then it won't set the default value: "Untitled" when sent to the database. I've looked online and have made sure that my settings were correct in phpmyadmin but it still won't set the default value. Any piece of advice is appreciated!
Here are my PHPmyadmin settings for the "Title" column:
These are my files:
addart.php
<form method="post" action="addtodb.php">
<label for="Title">
<h4>Title</h4>
</label>
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="Title">
</form>
addtodb.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'testdb';
$dbConnection = new mysqli($host, $user, $pass, $db);
if (mysqli_connect_errno()) {
printf("Could not connect to the mySQL database: %s\n", mysqli_connect_error());
exit();
}
if($_POST) {
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
$results = $dbConnection->query("INSERT INTO art
(Artwork, Title, Artist, Medium) VALUES
('$artwork','$title','$artist','$medium');");
if (!$results) {
echo 'Unable to insert into database.';
exit();
} else {
echo 'Successfully added!';
}
mysqli_close($dbConnection);
header("Location: galleryonly.php"); /* Redirect browser */
exit();
}
?>
$artwork = $_POST["Artwork"];
$medium = $_POST["Medium"];
$artist = $_POST["Artist"];
$title = $_POST["Title"];
if(!empty($title)) {
$sql = "INSERT INTO art (Artwork, Title, Artist, Medium) VALUES ('$artwork', '$title', '$artist', '$medium')";
} else {
$sql = "INSERT INTO art (Artwork, Artist, Medium) VALUES ('$artwork', '$artist', '$medium')";
}
$results = $dbConnection->query($sql);
You can try out this code.
If you're omitting the column, the default value will be set.
Because you have only one column with default value, you can stick with this code.
If you have more than one column with default value, you will need to make changes according to your requirements.
You have a bit of trick ahead of you, because you won't be able to use the Title column if you need the Default value.
// assuming use of proper method of sanitizing
// these values so we don't get SQL INJECTED!!
$artwork = 'artwork';
$title = 'title';
$artist = 'artist';
$medium = 'medium';
// make an array with the columns
$cols = explode(',', 'Artwork,Title,Artist,Medium');
// make an array with the values (that you sanitized properly!)
$vars = explode(',', 'artwork,title,artist,medium');
foreach ($cols as $i=>&$col) {
$var = ${$vars[$i]};
if ($col == 'Title') {
if (empty($var)) {
// don't add this column if empty
continue;
}
}
// otherwise (if not Title)
// add it to a column = "value" insert string
$pcs[] = "`$col` = '$var'";
}
// fortunately, we can insert with update syntax, too!
$query = 'insert into art set ';
$query .= implode(', ', $pcs);
use always small letters in
<input class="u-full-width"
type="text"
placeholder="Title of art"
id="Title"
name="title">

Mysql Public User chat to friend chat

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"]));
?>

Only first entry in list enters mysql table PHP even though trim is used

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.

undefined index id,fname,lastname in php

<html><head>
<title>Add record to my_database/my_table</title></head>
<body>
<?php
$self = $_SERVER['PHP_SELF'];
$id = $_POST['id'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
?>
<form action="<?php echo( $self ); ?>" method="post">
ID: <input type="text" name="id" size="3">
First Name: <input type="text" name="fname" size="8">
Last Name: <input type="text" name="lname" size="8"><br>
<input type="submit" value="Submit">
</form>
<?php
if( $id and $fname and $lname)
{
$conn=#mysql_connect( "localhost", "root", "" ) or die( "Err:Conn" );
select the specified database
$rs = #mysql_select_db( "add_record", $conn) or die( "Err:Db" );
create the query
$sql = "insert into my_table ( id, first_name, last_name ) values ( $id, \"$fname\", \"$lname\" )";
execute query
$rs = mysql_query( $sql, $conn );
if( $rs )
{
echo( "Record added:$id $fname $lname" );
}
}
?>
</body></html>
here am getting erro as undefined index id,fname,lastname and when i enter values in this am getting db error
At first when your page load $_POST['id'] value is empty because u ve'nt posted any value in $_POST[];
if(isset($_POST['submit'])){
//all your php code here like below
$self = mysql_real_escape_string($_SERVER['PHP_SELF']);
$id = mysql_real_escape_string($_POST['id']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
}
AND
$sql = "insert into my_table ( id, first_name, last_name ) values ( '$id', '$fname', '$lname' )";
By the way what is your db error??
Those POST values will only be set when the form is POSTed. You can use isset()
$id = isset($_POST['id'])? $_POST['id'] : NULL;
Same for others.
This happens because you have no conditions on that PHP code that will prevent it from executing the first time when the form is loaded. They should only execute when the form is submitted. You can wrap that PHP with
if(isset($_POST))
{
// Your existing database code here
}

Categories