How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>
Related
I currently have a loginsystem where a user is able to register and login as a user.
My system is based on PHP PDO.
When the user is logged in they should be able to upload a picture which is linked to their account.
Right now i have a fully functional loginsystem so thats great, and the user is currently able to upload a picture to the database, but he cant yet see it on the site.
Right now my problem is to make the pictures show up on the site.
I want the user to be able to see his OWN pictures that he uploaded, and not anybody elses pictures.
This is what i have so far! :)
This my Database!
TABLE PICTURES with the following rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
TABLE USERS with the following rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my CODE so far:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.INC.PHP
<?php
include "../upload.php";
//Find the ID of the USER
// session_start();
include_once 'dbh.inc.php';
$pictureTitle = ($_POST["filetitle"]);
$pictureText = ($_POST["filedesc"]);
//Fnd ID from the user
//$user = $_SESSION["u_id"];
$user = $_SESSION['u_id'];
$queryUserID = 'SELECT user_id from '.'users'. ' where user_name="'. $user.'";';
$stmt = $conn -> prepare($queryUserID);
$stmt -> execute();
$result = $stmt -> fetch(PDO::FETCH_ASSOC);
//FileDic
$fileDirectory = "../uploads/";
$fileHandled = $fileDirectory . basename($_FILES["file"]["name"]);
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileHandled)) {
//echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
$picture = 'INSERT INTO pictures (titlePicture, descPicture, userid, imageFullNamePicture)
VALUES (:titlePicture, :descPicture, :userid, :imageFullNamePicture);';
$stmt = $conn->prepare($picture);
$stmt -> bindParam(":titlePicture", $pictureTitle);
$stmt -> bindParam(":descPicture", $pictureText);
$stmt -> bindParam(":userid", $user);
//$stmt -> bindParam(":userid", $result['user_id']);
$stmt -> bindParam(":imageFullNamePicture", $fileHandled);
$stmt -> execute();
header("Location: ../upload.php?`Success");
?>
<?php } else {
header("Location: ../upload.php?Error");
//echo "Sorry, there was an error uploading your file.";
}
header("Location: ../upload.php");
UPLOAD.PHP
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="includes/upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['users'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="pictures">
<a target="file" href= <?php ?>>
<img class="pic" src= <?php echo $data['imageFullNamePicture']; ?>></a>
<div class="titlePicture"><?php echo $data['titlePicture']; ?> <br> </div>
<div class="descPicture" >Your description:</div>
<div class="text"><?php echo $data['titleDesc']; ?> <br> ?> </div>
</div>
<?php
}
};
?>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
So yea the problem is that i cant get the pictures that connects to the currently logged in user to show up on the page upload.php
I hope that somebody can help me! :)
EDIT!!!:
So i currently have this piece of code. IT should make the user see the pictures that he uploaded to the database, but it is very buggy. And it only shows one picture per user. Can somebody help make this work.
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic)
?>
<figure id="<?php echo $pic['id']; ?>">
<b><figcaption><?php echo $pic["titlePicture"] ?>
<img src = <?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
<?php
// }
}
?>
</div>
Your fetching the data as numerically indexed arrays PDO::FETCH_NUM, yet your using the keys in your code:
UPLOAD.INC.PHP
//instead of PDO::FETCH_NUM
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
...
<?php echo $data['imageFullNamePicture']; ?>
...
<?php }
Use PDO::FETCH_ASSOC instead.
Please don't do this with PDO:
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
If someone manages to get data in here name="' . $_SESSION['u_id'] . '" you've just defeated the whole purpose of preparing your SQL. It shouldn't matter where that data came from, you never know when a simple coding mistake or something will allow user data into a session variable.
$user_data = 'SELECT * FROM users INNER JOIN pictures on users.user_id
= pictures.userid WHERE name=:u_id';
$stmt = $conn->prepare($user_data);
$stmt->execute(['u_id'=>$_SESSION['u_id']]);
It's that easy to prepare it properly. You don't really need to even use bind whatever with PDO, unless you wan't to restrict the Type. But I think it's also the only way to do LIMIT :limit. Anyway I almost never use them. In general both PHP and MySQL are smart enough to do the proper type casting.
PS. don't forget to call session_start() if your using $_SESSION or none of that will work. I didn't see it in the code that was posted, so I have to mention it.
What I am trying to do is modify some attributes in my database. The way I want to do it, is to have a dropdown menu that is populated with options (in this case, student names) from the table I am calling, and then populating text fields with the information that pertains to that specific student, that can then be edited and then submitted to the database. So far, my drop down menu works. It fills itself with the appropriate attributes. My problem comes when I'm trying to populate the text fields with the other attributes. I opened up the console to see if I was getting any errors (because nothing was happening after I selected a student) and it said there was an error 500 with my POST.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<?php
# Perform database query
$query = "SELECT * FROM student";
$result = $conn->query($query) or die('Query 1 failed: ' . mysql_error());
?>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php
while ($row = $result->fetch_assoc())
{
echo '<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>';
}
?>
</select>
<div>
<label for="element_5_1">First Name</label>
<input id="element_5_1" name="element_5_1" class="element text large" type="text">
</div>
<div>
<span class="floatLeft">
<label for="element_5_3">Last Name</label>
<input id="element_5_3" name="element_5_3" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label for="element_5_4">Major</label>
<input id="element_5_4" name="element_5_4" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label for="element_5_5">Credits Earned</label>
<input id="element_5_5" name="element_5_5" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
function makeAjaxRequest(studentFirstName)
{
$.ajax({
type: "POST",
data: { studentFirstName: studentFirstName },
dataType: "json",
url: "process_ajax.php",
success: function(json)
{
insertResults(json);
},
failure: function (errMsg)
{
alert(errMsg);
}
});
}
$("#studentSelect").on("change", function()
{
var id = $(this).val();
if (id === "0")
{
clearForm();
}
else
{
makeAjaxRequest(id);
}
});
function insertResults(json)
{
$("#element_5_1").val(json["studentFirstName"]);
$("#element_5_3").val(json["studentLastName"]);
$("#element_5_4").val(json["major"]);
$("#element_5_5").val(json["creditsEarned"]);
}
function clearForm()
{
$("#element_5_1, #element_5_3, #element_5_4, #element_5_5").val("");
}
</script>
I then have a separate ajax processing file
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)) {
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
?>
I hope I've given enough information for someone to be able to spot my errors. Thank you!
Parse error line 22.
<?php
$host = "********.mysql.database.azure.com";
$username = "************";
$password = "*******";
$db_name = "**********";
//Establishes the connection
$conn = mysqli_init();
mysqli_real_connect($conn, $host, $username, $password, $db_name, 3306);
if (mysqli_connect_errno($conn)){
die('Failed to connect to MySQL: '.mysqli_connect_error());
$studentName = $_POST['studentFirstName'];
$query = "SELECT * FROM student";
$result = mysql_query($query) or die('Query 2 failed: ' . mysql_error());
while ($row = mysql_fetch_assoc($result)) {
if ($studentName == $row['studentFirstName']){
echo json_encode($row);
}
}
}
?>
You have to change also your javascript
function insertResults(json)
{
$("#element_5_1").val(json.studentFirstName);
$("#element_5_3").val(json.studentLastName);
$("#element_5_4").val(json.major);
$("#element_5_5").val(json.creditsEarned);
}
After 4 hours of trial and error, this is the code I came up with that works in populating the input fields. I'm pretty sure your error was the fact that your
<option value="' . $row['studentID'] . '" > "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
should have been
<option value="' . $row['studentID'] . '" name="studentFirstName"> "' . $row['studentFirstName'] . '" "' . $row['studentLastName'] . '"</option>
anyways onto my code:
config.php
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = ""; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
<?php
include("config.php");
$sql = "SELECT * FROM messaging";
$result = $conn->query($sql);
$conn->close();
?>
<!Doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<label for="studentSelect">Student Name: </label>
<select id="studentSelect">
<option value="0">Please select</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?php echo $row['msg_id']; ?>" name="studentFirstName" id="studentFirstName">"<?php echo $row['msg_from'] ?>" "<?php echo $row['msg_to'] ?>"</option>
<?php } ?>
</select>
<div>
<span class="floatLeft">
<label>First Name</label>
<input id="populate_first_name" class="element text large" type="text">
</span>
<span class="floatLeft">
<label>Last Name</label>
<input id="populate_last_name" class="element text medium" style="width:14em" type="text">
</span>
<span style="float:left">
<label>Major</label>
<input id="populate_major" class="element text medium" style="width:4em" type="text">
</select>
</span>
<span style="float:left">
<label>Credits Earned</label>
<input id="populate_credits_earned" class="element text medium" style="width:6em" type="text">
</span>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#studentSelect").change(function(){
var studentFirstName = $(this).val();
$.ajax({
url: 'process_ajax.php',
type: 'post',
data: {studentFirstName:studentFirstName},
dataType: 'json',
success:function(response) {
var len = response.length;
for( var i = 0; i<len; i++) {
var studentFirstName = response[i]['studentFirstName'];
var studentLastName = response[i]['studentLastName'];
var major = response[i]['major'];
var creditsEarned = response[i]['creditsEarned'];
$("#populate_first_name").val(studentFirstName);
$("#populate_last_name").val(studentLastName);
$("#populate_major").val(major);
$("#populate_credits_earned").val(creditsEarned);
}
}
});
});
});
</script>
</body>
</html>
process_ajax.php
<?php
include("config.php");
$studentName = $_POST['studentFirstName']; // department id
$sql = "SELECT * FROM student";
$result = mysqli_query($con,$sql);
$users_arr = array();
while( $row = mysqli_fetch_array($result) ) {
if ($row['msg_id'] == $studentName) {
$studentFirstName = $row['studentFirstName'];
$studentLastName = $row['studentLastName'];
$major = $row['major'];
$creditsEarned = $row['creditsEarned'];
$users_arr[] = array("studentFirstName" => $studentFirstName, "studentLastName" => $studentLastName, "major" => $major, "creditsEarned" => $creditsEarned);
}
}
// encoding array to json format
echo json_encode($users_arr);
?>
Try it out and lemme know if it works
Whenever I enter an id number in text box and click scan button, i get data from database and it is displayed below the text box in a predefined format. Now when i enter another id and hit scan, the new data thus retreived replaces the older one. I want it to be displayed below the already existing data on the page.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title> ShopNGo </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header id="header">
<div class="container">
<form name="products" method="POST">
<br><br>
<button type="submit" name="scan" id="scan"> <h1> SCAN! </h1> </button>
<br><br><br>
<input type="text" name="id">
</form>
</div>
</header>
<div class="main">
<table border="0">
<?php
if (isset($_POST["scan"])) {
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection Failed:" . mysqli_connect_error());
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<tr> <table border='0'> <tr>";
echo "<img src='$row[img]'>";
echo "<br>";
echo $row["name"];
echo "<br>";
echo $row["price"];
echo "</tr> </table> </tr>";
}
}
mysqli_close($conn); }
?>
</table>
</div>
</body>
</html>
please help me !!
also it would be a great help if u can suggest some improvements in the existing code other than what i asked for... Thank you so much !!
use ajax to post your id to another php script that checks id for data, put the html into a string variable and then echo it at the end. You can use the ajax success callback to append the data
$.ajax({
type: "POST",
url: url,
data: id,
success: function(data){
$('#targetDiv').append(data);
}
});
php script:
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row =
mysqli_fetch_assoc($result))
{
$element = "<tr> <table border='0'> <tr>";
$element .= "<img src='$row[img]'>";
$element .= "<br>";
$element .=$row["name"];
$element .= "<br>";
$element .= $row["price"];
$element .= "</tr> </table> </tr>";
}
}
echo $element;
I am trying to input a value (Rating) from the database when an item is selected. I need to also be able to update that rating and then put that value into another table.
My problem is that I'm trying to figure out how to make the value in the text box be related to the selection made in the drop down. I've found coding to make another option box but cannot figure out how to make that a text box.
REWORDING: Originally when I posted the question I thought it was possible to do this without JQuery and was trying to copy the for loop and run a while loop to populate the text box. I now know that isn't possible and would like to figure out how to run a script to populate a text box on change for the drop down box. The problem being the function has to be connected to the database as well as the drop down.
1. pull the data for the drop down (from the JOURNAL table). 2. Select a journal from that drop down 3. Inside the JOURNAL table a JournalRating has been assigned to every journal pull that value and place inside a textbox.
What I've tried to do is
<?php
include 'dbc.php';
connect();
//insert form values into database
$sql = "SELECT JournalName, JournalID, Rating, JournalActive from JOURNAL where JournalActive = 1;";
//Can take out JournalActive if we do not want it
$result = mysqli_query($conn, $sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
$sql2 = "SELECT FName, LName, FacultyID from FACULTY where FacultyActive = 1;";
//Can take out JournalActive if we do not want it
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
echo "there was an issue";
}
//array to hold all of the data
$journals = array();
//print out all of the first names in the database
$rownumber = 0;
while ($row = mysqli_fetch_assoc($result)) {
$journals[$rownumber][0] = $row['JournalName'];
$journals[$rownumber][1] = $row['JournalID'];
$journals[$rownumber][2] = $row['JournalRating'];
$journals[$rownumber][3] = $row['JournalActive'];
$rownumber++;
}
$faculty = array();
//print out all of the first names in the database
$rownum = 0;
while ($row = mysqli_fetch_assoc($result2)) {
$faculty[$rownum][0] = $row['FName'];
$faculty[$rownum][1] = $row['LName'];
$faculty[$rownum][2] = $row['FacultyID'];
$rownum++;
}
?>
<!DOCTYPE html>
<head>
<link href="styles.css" rel="stylesheet">
<h1> Miami University </h1>
<h4> Information Systems and Analytics Department </h4>
<script>
(function($){
$(function(){
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('Rating'));
});
});
})(jQuery);
</script>
</head>
<body>
<div class="StyleDiv" >
<!-- coding for journal -->
<form id="form1" name="form1" method="post" action="RR2.php">
<label for="FacultyID">Faculty Name</label>
<select multiple="multiple" name="FacultyID[]" id="FacultyID">
<?php
for($i = 0; $i < sizeof($faculty); $i++) {
print "<option value=\"" . $faculty[$i][2] . "\">" . $faculty[$i][0] .' '. $faculty[$i][1] . "</option>\r\n";
}
?>
</select>
<br class="clear" />
<br class="clear" />
<label for="JournalID">Journal Name</label>
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
<br class="clear"/>
<label for="JournalRating">Journal Rating</label><input type="text" name="JournalRating" id="JournalRating" />
<br class="clear" />
<!-- coding for publication -->
<label for="Title">Publication Title</label><input type="text" name="PubID" id="PubID" />
<br class="clear" />
<label for="Year">Year</label><input type="text" name="Year" id="Year" />
<br class="clear" />
<label for="Volume">Volume</label><input type="text" name="Volume" id="Volume" />
<br class="clear" />
<label for="Issue">Issue</label><input type="text" name="Issue" id="Issue" />
<br class="clear" />
<label for="Comments">Comments</label><textarea name="Comments" id="Comments" cols="45" rows="5"></textarea>
<br class="clear" />
<input type="submit" name="Submit" id="Submit" value="Submit" />
<br class="clear" />
</br>
</br>
</div>
</form>
<?php
//Post Parameters
$JournalID = $_POST['JournalID'];
//for($i = 0; $i < sizeof($journals); $i++) {
//if ($JournalID = $journals[$i][1]) {
//$JournalName = $journals[$i][0];
//}
//}
$Year = $_POST['Year'];
$Comments = $_POST['Comments'];
$Volume = $_POST['Volume'];
$Issue = $_POST['Issue'];
$Title = $_POST['Title'];
$JournalRating = $_POST['JournalRating'];
$FacultyMemID = $_POST['FacultyID'];
//Query
//INSERT
$stmt = $conn->prepare(" INSERT INTO PUBLICATION ( JournalID, Year, Comments, Volume, Issue, Title, JournalRating ) VALUES ( ?, ?, ?, ?, ?, ?, ? )");
$stmt->bind_param('sssssss', $JournalID, $Year, $Comments, $Volume, $Issue, $Title, $JournalRating);
$stmt->execute();
$pubID = $stmt->insert_id;
$facmemid = 0;
$stmt = $conn->prepare(" INSERT INTO FACULTYPUBLICATIONS ( FacultyID, PubID ) VALUES ( ?, ? )");
$stmt->bind_param('ii', $facmemid, $pubID);
//for ($_POST['FacultyID'] as $FacultyMemID) {
for($i = 0; $i < sizeof($FacultyMemID); $i++) {
$facmemid = $FacultyMemID[$i];
$stmt->execute();
}
mysqli_close($conn);
?>
</body>
</html>
Add the rating to your HTML using a data attribute:
<select name="JournalID" id="JournalID">
<?php
for($i = 0; $i < sizeof($journals); $i++) {
print "<option value=\"" . $journals[$i][1] . "\" data-rating=\"" . $journals[$i][2] . "\">" . $journals[$i][0] . "</option>\r\n";
}
?>
</select>
Then you can access this using jQuery .data():
(function($) {
$(function() {
$("#JournalID").on('change', function() {
$("#JournalRating").val($(this).find("option:selected").data('rating'));
});
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="JournalID">
<option>Select a journal</option>
<option value="1" data-rating="3">Journal #1</option>
<option value="2" data-rating="2">Journal #2</option>
<option value="3" data-rating="5">Journal #3</option>
</select>
<br>
Rating: <input id="JournalRating">
I'm trying to create a form for my system, user could add the numbers of input fields, the input fields are mostly drop down box with the options coming from tables in the database. The forms would insert the data into two different database. But it shows error of "Array to string conversion" Right now the data only inserted into the first table. Here's what I'd done so far
My form's code:
<form method="post" name="maklumat_akaun" action="proses_daftar_akaun.php">
<label for="NoAkaun">No. Akaun</label>
<input type="text" id="NoAkaun" name="NoAkaun" class="required input_field" required/>
<div class="cleaner_h10"></div>
<label for="KodDaerah">Daerah</label>
<?php
include('dbase.php');$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodBahagian">Bahagian</label>
<?php
$sql = "SELECT KodBahagian, NamaBahagian FROM kodbahagian";
$result = mysql_query($sql);
echo "<select name='KodBahagian' id='KodBahagian' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodBahagian'].">" .$kod['NamaBahagian']."</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="KodKategori">Kategori Akaun</label>
<?php
$sql = "SELECT KodKategori, NamaKategori , SubKategori FROM kodkategori";
$result = mysql_query($sql);
echo "<select name='KodKategori' id='KodKategori' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodKategori'].">" .$kod['NamaKategori']." (".$kod['SubKategori'].")</OPTION>";
}
echo "</select>";
?>
<div class="cleaner_h10"></div>
<label for="Tarif">Tarif</label>
<input type="text" maxlength="4" size="4" id="Tarif" name="Tarif" class="required year_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')">
<div class="cleaner_h10"></div>
<!-----------------------------------------------------------//-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var max_fields = 25; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initial text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div>'+
'<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name=\'KodLokasi[]\' id=\'KodLokasi[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']. "</OPTION>";
}
echo "</select>";
?> </td> </tr>'+
'<tr> <td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name=\'KodJenisAkaun[]\' id=\'KodJenisAkaun[]\' class=\'input_field\' required ><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']. "</OPTION>";
}
echo "</select>";
?> </td>'+
'<td> <input type="text" name="NoTelefon[]" id="NoTelefon[]" value="0" class="required input_field"> </td>' +
'Batal</tr></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
});
});
</script>
<fieldset>
<div class="input_fields_wrap">
<h3 class="add_field_button">Add More Fields</h3>
<table>
<tr>
<td> <label for="KodLokasi">Lokasi</label> </td> <td> <label for="KodJenisAkaun">Jenis Akaun</label> </td> <td> <label>No.Telefon:</label> </td>
</tr>
<tr>
<td> <?php
$sql = "SELECT KodLokasi, NamaLokasi FROM kodlokasi";
$result = mysql_query($sql);
echo "<select name='KodLokasi[]' id='KodLokasi' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodLokasi'].">" .$kod['NamaLokasi']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <?php
$sql = "SELECT KodJenisAkaun, NamaJenisAkaun FROM kodjenisakaun";
$result = mysql_query($sql);
echo "<select name='KodJenisAkaun[]' id='KodJenisAkaun' class='input_field' required /><option></option>";
while($kod = mysql_fetch_array($result)){
echo "<option value=".$kod['KodJenisAkaun'].">" .$kod['NamaJenisAkaun']."</OPTION>";
}
echo "</select>";
?>
</td>
<td> <input type="text" name="no_telefon[]" value="0" class="required input_field" onkeyup="this.value=this.value.replace(/[^0-9.]/g,'')"> </td>
</tr>
</table>
</div>
</fieldset>
<!-----------------------------------------------------------//-->
<div class="cleaner_h10"></div>
<div class="cleaner_h10"></div>
<input type="submit" value="Daftar" id="submit" name="register-submit" class="submit_btn" />
<input type="reset" value="Batal" id="reset" name="reset" class="submit_btn" />
</table>
</form>
While this is my code for the inserting process.
<?php
require("dbase.php");
if ($_POST) {
$NoAkaun = isset($_POST['NoAkaun']) ? $_POST['NoAkaun'] : '';
$KodBahagian = isset($_POST['KodBahagian']) ? $_POST['KodBahagian'] : '';
$Tarif = ISSET($_POST['Tarif']) ? $_POST['Tarif'] : '';
$KodDaerah = isset($_POST['KodDaerah']) ? $_POST['KodDaerah'] : '';
$KodKategori = isset($_POST['KodKategori']) ? $_POST['KodKategori'] : '';
$NoTelefon = isset($_POST['NoTelefon']) ? $_POST['NoTelefon'] : '';
$KodLokasi = isset($_POST['KodLokasi']) ? $_POST['KodLokasi'] : '';
$KodJenisAkaun = isset($_POST['KodJenisAkaun']) ? $_POST['KodJenisAkaun'] : '';
$akaun_idAkaun = isset($_POST['akaun_idAkaun']) ? $_POST['akaun_idAkaun'] : '';
$sql = mysql_query("INSERT INTO maklumatakaun VALUES ('', '$NoAkaun' , '$KodBahagian' , '$KodDaerah' , '$KodKategori' , '$Tarif' )");
$akaun_idAkaun = mysql_insert_id();
foreach ($NoTelefon AS $i => $telefon) {
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
}
echo "<script type='text/javascript'> alert('AKAUN BERJAYA DIDAFTARKAN')</script> ";
echo "<script type='text/javascript'>window.location='pilih_kategori_daftar.php'</script>";
}
?>
Can anyone help me figure this out?
The error "Array to string conversion" means you are using an array as a string somewhere in your code. That error message is usually followed by a filename and line number which should help you narrow down your search. One helpful way to see what is contained within a variable is to use the following:
echo '<pre>'; print_r($stuff); die();
If the error is happening on a line inside of a while loop you should put the echo '' before the while and the die(); after so that you can see all instances of the problem within the loop.
I found your problem on this statement
$sql = mysql_query("INSERT INTO detailakaun VALUES ('', '$KodLokasi[$i]', '$KodJenisAkaun' , '$telefon' , '$akaun_idAkaun' )");
$KodJenisAkaun is an array and you use it as a string