Brett Muldrow Ответов: 2

Нужна помощь в отображении данных из базы данных на PHP страницу в таблице


Мне нужна помощь в отображении данных из таблицы базы данных phpMyAdmin на страницу php в таблице. Я все время получаю неопределенную проблему с индексом, может ли кто-нибудь мне помочь? Главная проблема находится внутри showrecords.php код страницы.

Notice: Undefined index: songtitle in C:\wamp64\www\showrecords.php on line 64

Notice: Undefined index: songartist in C:\wamp64\www\showrecords.php on line 65

Notice: Undefined index: songalbum in C:\wamp64\www\showrecords.php on line 66

Notice: Undefined index: yearreleased in C:\wamp64\www\showrecords.php on line 67

Notice: Undefined index: monthplayed in C:\wamp64\www\showrecords.php on line 68

Notice: Undefined index: dayplayed in C:\wamp64\www\showrecords.php on line 69

Notice: Undefined index: dateplayed in C:\wamp64\www\showrecords.php on line 70

Notice: Undefined index: timeplayed in C:\wamp64\www\showrecords.php on line 71

Вот код для HTML-страницы:

<html lang="en">
	<head>
	<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="crossorigin="anonymous"></script>
	<script type = "javascript">
	function submitdata()
{
 var songtitle  =document.getElementById( "songtitle" );
 var songartist = document.getElementById( "songartist" );
 var songalbum =document.getElementById( "songalbum" );
 var yearreleased  =document.getElementById( "yearreleased" );
 var monthplayed =document.getElementById( "monthplayed" );
 var dayplayed =document.getElementById( "dayplayed" );
 var dateplayed  =document.getElementById( "dateplayed" );
 var timeplayed =document.getElementById( "timeplayed" );
 $.ajax({
  type: 'post',
  url: 'insert.php',
  data: {
  Song_Title: songtitle,
  Song_Artist: songartist
  Song_Album: songalbum,
  Year_Released: yearreleased,
  Month_Played: monthplayed,
  Day_of_the_Week_Played: dayplayed,
  Date_Played: dateplayed,
  Time_Played: timeplayed

  },
  success: function (response) {
   $('#success__para').html("Your data will be saved");
  }
 });
	
 return false;
}

</script>

	 <script src="Nonrefresh.js"></script> 
		<style>
body {
  margin: 0;
  min-width: 250px;
}

/* Include the padding and border in an element's total width and height */
* {
  box-sizing: border-box;
}

/* Remove margins and padding from the list */
ul {
  margin: 0;
  padding: 0;
}

/* Style the list items */
ul li {
  cursor: pointer;
  position: relative;
  padding: 12px 8px 12px 40px;
  background: #eee;
  font-size: 18px;
  transition: 0.2s;
  
  /* make the list items unselectable */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

/* Set all odd list items to a different color (zebra-stripes) */
ul li:nth-child(odd) {
  background: #f9f9f9;
}

/* Darker background-color on hover */
ul li:hover {
  background: #ddd;
}

/* When clicked on, add a background color and strike out text */
ul li.checked {
  background: #888;
  color: #fff;
  text-decoration: line-through;
}

/* Add a "checked" mark when clicked on */
ul li.checked::before {
  content: '';
  position: absolute;
  border-color: #fff;
  border-style: solid;
  border-width: 0 2px 2px 0;
  top: 10px;
  left: 16px;
  transform: rotate(45deg);
  height: 15px;
  width: 7px;
}

/* Style the close button */
.close {
  position: absolute;
  right: 0;
  top: 0;
  padding: 12px 16px 12px 16px
}

.close:hover {
  background-color: #f44336;
  color: white;
}

/* Style the header */
.header {
  background-color: #f44336;
  padding: 30px 40px;
  color: white;
  text-align: center;
}

/* Clear floats after the header */
.header:after {
  content: "";
  display: table;
  clear: both;
}

/* Style the input */
input {
  border: none;
  width: 75%;
  padding: 10px;
  float: left;
  font-size: 16px;
}

/* Style the "Add" button */
.addBtn {
  padding: 10px;
  width: 25%;
  background: #d9d9d9;
  color: #555;
  float: left;
  text-align: center;
  font-size: 16px;
  cursor: pointer;
  transition: 0.3s;
}

.addBtn:hover {
  background-color: #bbb;
}
	</style>
	<meta charset="utf-8" />
        <title>Music Project Form</title>
	</head>
	
	<body>
	
	

	<header><h1><center>Music Input Form</center></header>

	

	
	<script type = "text/javascript" src = "SubmitForm.js"></script>
	<script type = "text/javascript" src = "Nonrefresh.js"></script>
	<center><div id="myDIV" class="header">
	
	<center><form action="insert.php" method="post" name="Music Data" target="Music Randomizer.html">
					<input type="varchar" name = "songtitle" id="songtitle" placeholder="Song Title" style="margin: 5px auto;"><BR>
		 			<input type="varchar" name = "songartist" id="songartist" placeholder="Song Artist" style="margin: 5px auto;">
		 			<input type="varchar" name = "songalbum" id="songalbum" placeholder="Song Album" style="margin: 5px auto;">
		 			<input type="year" name = "yearreleased" id="yearreleased" placeholder="Year Released" style="margin: 5px auto;">
		 			<input type="text" name = "monthplayed" id="monthplayed" placeholder="Month Played" style="margin: 5px auto;">
					<input type="text" name = "dayplayed" id="dayplayed" placeholder="Day of the Week Played" style="margin: 5px auto;">
		 			<input type="varchar" name = "dateplayed" id="dateplayed" placeholder="Date Played" style="margin: 5px auto;">
		 			<input type="text" name = "timeplayed" id="timeplayed" placeholder="Time Played" style="margin: 5px auto;">
		
		<input type = "button" onclick = "submitForm()" value = "Add Song"><input type = "reset"  value = "Clear"></center>
	</form>	
	
	
	
	


	</body>
</html>



Вот код для страницы вставки:

<?php 

	$con = mysqli_connect('localhost', 'root', 'root', 'music_database');
	
	if(!$con)
	{
		echo 'Not Connected to Server!';
	}

	if(!mysqli_select_db($con, 'music_database'))
	{
		echo 'Database Not Selected!';
	}
	
	$songtitle = $_POST['songtitle'];
    $songartist = $_POST['songartist'];
    $songalbum  = $_POST['songalbum'];
    $yearreleased = $_POST['yearreleased'];
    $monthplayed = $_POST['monthplayed'];
    $dayplayed = $_POST['dayplayed'];
    $dateplayed = $_POST['dateplayed'];
    $timeplayed = $_POST['timeplayed'];

	$query =  mysqli_query($con,"INSERT INTO `month1` (Song_Title, Song_Artist, Song_Album, Year_Released, Month_Played, Day_of_the_Week_Played, Date_Played, Time_Played) VALUES ('$songtitle', '$songartist', '$songalbum', '$yearreleased', '$monthplayed', '$dayplayed', '$dateplayed', '$timeplayed')") or die(mysqli_error($con));
	
	
	
	mysqli_close($con);
	
	
?> 



Вот код для showrecords.php страница:

<html>
 <head>
  <title>Music Database</title>
 </head>
 <body>
 <html lang="en">
   <head>
   <style>
	table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
	}
</style>
        <meta charset="utf-8" />
        <title>Music List Storage</title>
    </head>
	<body>
	<center>
		<header><h1><center>Music Playlist for Month 1</center></header>
		<?php

		$con = mysqli_connect('localhost', 'root', 'root', 'music_database');
	
		if(!$con)
		{
			die("Can not connect: " . mysqli_error($con));
		}

		if(!mysqli_select_db($con, 'music_database'))
		{
			echo 'Database Not Selected!';
		}
	
	
		$sql = "SELECT * FROM month1";
		$query = mysqli_query($con, $sql);
		if (!$query) 
		{ // add this check.
			die('Invalid query: ' . mysqli_error($con));
		} else{
	
		
		if (isset($_GET['title'])) {
			$output = $_GET['title'];
		}
	
		echo "<table border=1>
		<tr>
		<th>Song Title</th>
		<th>Song Artist</th>
		<th>Song Album</th>
		<th>Year Released</th>
		<th>Month Played</th>
		<th>Day of the Week Played</th>
		<th>Date Played</th>
		<th>Time Played</th>
		</tr>";

		
	
		  
          while($record = mysqli_fetch_assoc($query))
		  {
			  
			echo "<tr>";
            echo "<td>" . $record['songtitle'] . "</td>";
            echo "<td>" . $record['songartist'] . "</td>";
			echo "<td>" . $record['songalbum'] . "</td>";
			echo "<td>" . $record['yearreleased'] . "</td>";
			echo "<td>" . $record['monthplayed'] . "</td>";
			echo "<td>" . $record['dayplayed'] . "</td>";
			echo "<td>" . $record['dateplayed'] . "</td>";
			echo "<td>" . $record['timeplayed'] . "</td>";
			echo "</tr>";
          }
		  
		 echo "</table>";
		} 
		 mysqli_close($con);
        ?>
		  
		
   
	 

		
  
  <ul id = "Music Playlist">
	
	</ul>
	<center><button id="shuffle" onclick="shuffle" type="button">Shuffle Music Playlist</button>
	
	<script>
		var myNodelist = document.getElementsByTagName("LI");
var i;
for (i = 0; i < myNodelist.length; i++) {
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  myNodelist[i].appendChild(span);
}

// Click on a close button to hide the current list item
var close = document.getElementsByClassName("close");
var i;
for (i = 0; i < close.length; i++) {
  close[i].onclick = function() {
    var div = this.parentElement;
    div.style.display = "none";
  }
}





// Create a new list item when clicking on the "Add" button

function newElement() {
  var li = document.createElement("li");
  var inputValue = document.getElementById("songtitle").value;
  var t = document.createTextNode(inputValue);
  li.appendChild(t);
  if (inputValue === '') {
    alert("You must write something!");
  } else {
    document.getElementById("Music Playlist").appendChild(li);
  }
  document.getElementById("Music Playlist").value = "";

  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u00D7");
  span.className = "close";
  span.appendChild(txt);
  li.appendChild(span);

  for (i = 0; i < close.length; i++) {
    close[i].onclick = function() {
      var div = this.parentElement;
      div.style.display = "none";
    }
  }
  
  <script type="text/javascript">


  
	document.forms["Music Data"].submit();
	document.forms["songtitle"].reset();
	document.forms["songartist"].reset();
	document.forms["songalbum"].reset();
	document.forms["yearreleased"].reset();
	document.forms["monthplayed"].reset();
	document.forms["dayplayed"].reset();
	document.forms["dateplayed"].reset();
	document.forms["timeplayed"].reset();
}

var list = document.getElementById("Music Playlist"), button = document.getElementById("shuffle");
function shuffle(items)
{
    var cached = items.slice(0), temp, i = cached.length, rand;
    while(--i)
    {
        rand = Math.floor(i * Math.random());
        temp = cached[rand];
        cached[rand] = cached[i];
        cached[i] = temp;
    }
    return cached;
}
function shuffleNodes()
{
    var nodes = list.children, i = 0;
    nodes = Array.prototype.slice.call(nodes);
    nodes = shuffle(nodes);
    while(i < nodes.length)
    {
        list.appendChild(nodes[i]);
        ++i;
    }
}
button.onclick = shuffleNodes;


	</script>
 </body>
 
</html>


Что я уже пробовал:

Я уже переключился на mysqli, так что этого не может быть.

2 Ответов

Рейтинг:
2

W∴ Balboos, GHB

$query =  mysqli_query($con,"INSERT INTO `month1` (Song_Title, Song_Artist, Song_Album, Year_Released, Month_Played, Day_of_the_Week_Played, Date_Played, Time_Played) VALUES ('$songtitle', '$songartist', '$songalbum', '$yearreleased', '$monthplayed', '$dayplayed', '$dateplayed', '$timeplayed')") or die(mysqli_error($con));

и
echo "" . $record['songtitle'] . "";
echo "" . $record['songartist'] . "";
echo "" . $record['songalbum'] . "";
echo "" . $record['yearreleased'] . "";
echo "" . $record['monthplayed'] . "";
echo "" . $record['dayplayed'] . "";
echo "" . $record['dateplayed'] . "";
echo "" . $record['timeplayed'] . "";


и
$sql = "SELECT * FROM month1";



При указании имен столбцов в запросе данных необходимо использовать правильную заглавную букву. Когда вы используете '*', то какой бы случай ни был в таблице, это то, что вам нужно использовать. Это все строчные буквы или как в вашем запросе вставки, или что-то еще, вообще?


Рейтинг:
2

Peter Leow

Глядя на инструкцию SQL insert, имена столбцов для таблицы month1 должны быть следующими

Song_Title, Song_Artist, Song_Album, Year_Released, Month_Played, Day_of_the_Week_Played, Date_Played, Time_Played

То
$record = mysqli_fetch_assoc($query)

помещает каждую строку в ассоциативный массив, ключами которого являются имена столбцов таблицы, т. е.
$record['Song_Title']

нет
$record['songtitle']

То же самое касается и остальных.