Adding Multiple Rows into Database - javascript

I'm having issue in adding multiple rows of data into database for the form name courseoutlineimage are attached here. I have tried use array statement but it still not support my code and i couldn't find where is the mistake. Please help me to correct my code.
Script Code:
<script>
$('document').ready(function(){
$('#btn').click(function(e){
e.preventDefault();
$('.apsection').append('Course Outline: <input type="text" style="width: 800px;" name="courseoutline[]" class="form-contro" placeholder="Enter your Course Outline"><br>');
});
});
</script>
Form Code:
<div class="tab"><h5>Section 3: Course Content Outline</h5>
<div class="apsection">
Course Outline : <input type="text" style="width: 800px;" name="courseoutline[]" class="form-contro" placeholder="Enter your Course Outline"><br>
</div>
<button id="btn" class="btn btn-warning">Add More</button>
</div>
Database Code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "adminpanel";
//connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(!$conn){
die("connection failure " . mysqli_connect_error());
}
$count = count($_POST['courseoutline']);
for ($i=0; $i <$count ; $i++) {
mysqli_query($sqlres);
$sqlres = "INSERT INTO course_content (courseoutline, coursecode) VALUES ('{$_POST['courseoutline'][$i]}','$coursecode')";
}
mysqli_close($conn);
?>

Use foreach instead of.
Database Code:
foreach($_POST['courseoutline'] as $value) {
$sqlres = "INSERT INTO course_content (courseoutline, coursecode) VALUES ($value,'$coursecode')";
}

Related

How to work in php page with more mysql database connections in real-time

I have three mysql databases with same structure (same tables). Then I have one query, that return different results from each database.
I want have one php page, where I will have radiobutton, listbox, etc. (without submit button), where I will choose database (DB1/DB2/DB3) and then I will see the results according to the selected database (I want it in real-time, without submit button).
What I have:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<?php
include_once ('connection_db_1.php');
?>
<body>
<form action="">
<select name="database">
<option value="DB1">DB1</option>
<option value="DB2">DB2</option>
<option value="DB3">DB3</option>
</select>
</form>
<?php
include ('queries.php');
$test_1 = mysqli_query($mysqli_db, $test);
echo "
<table>
<thead>
<tr>
<th>Column_1</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($test_1)) {
echo "<form method=\"post\"><tr>";
echo "<td>" . $row['Column_1'] . "</td>";
echo "</tr></form>";
}
echo "</table><br>";
mysqli_close($mysqli_db);
?>
</body>
</html>
queries.php
<?php
$test = "select Column_1 from TEST; ";
?>
connection_db_1.php
<?php
// Connection data
$servername = "servename";
$username = "username";
$password = "pasword";
$dbname = "dbname_1";
// Create connection
$mysqli_db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli_db->connect_error) {
die("Connection failed: " . $mysqli_db->connect_error);
}
?>
connection_db_2.php
<?php
// Connection data
$servername = "servename";
$username = "username";
$password = "pasword";
$dbname = "dbname_2";
// Create connection
$mysqli_db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli_db->connect_error) {
die("Connection failed: " . $mysqli_db->connect_error);
}
?>
I think, that I need some javascript/ajax solution, but I dont know how use it effectively.
Thank you for some advice.
Per now I can't see you showing any examples where you use or have implemented any ajax handler.
I could suggest you use either plain Javascript or jQuery (by including a javascript library, see her
What you could do, before considering implementing AJAX, is the following (it will include the database after first selection and form submission):
<?php
if (isset($_POST["database"])) {
$db = $_POST["database"];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<?php
include_once("connection_db_" . $db . ".php"); /* This will include the selected connection */
?>
<body>
<form action="" method="post">
<select name="database">
<option value="1">DB1</option>
<option value="2">DB2</option>
<option value="3">DB3</option>
</select>
</form>
<?php
include('queries.php');
$test_1 = mysqli_query($mysqli_db, $test);
echo "
<table>
<thead>
<tr>
<th>Column_1</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($test_1)) {
echo "<form method=\"post\"><tr>";
echo "<td>" . $row['Column_1'] . "</td>";
echo "</tr></form>";
}
echo "</table><br>";
mysqli_close($mysqli_db);
?>
</body>
</html>
Are the databases on the same server? If so, you only need one connection to the server. You can make the query by adding the database name in the query:
select Column_1 from dbname_1.TEST
or
select Column_1 from dbname_2.TEST

Changing innerHTML in php errors

I am beginner in PHP.
My CODE
<?php
session_start();
$username = "ADMIN";
$host = "localhost";
$password = "chmuhammadsohaib123";
$database = "USER";
$con = mysqli_connect($host, $username, $password, $database);
$USERNAME = $_POST["lusername"];
$PASSWORD = $_POST["lpassword"];
if (isset($_POST["login"])) {
if (isset($_POST["loggedin"])) {
setcookie("RAUSERNAME", $USERNAME);
setcookie("RAPASSWORD", $PASSWORD);
}
$_SESSION["SRAUSERNAME"] = $USERNAME;
$_SESSION["SRAPASSWORD"] = $PASSWORD;
}
if (isset($_POST["login"])) {
$data = mysqli_query($con, "SELECT * FROM `INFO` WHERE `USERNAME` = '$USERNAME'");
if (mysqli_num_rows($data)>0) {
echo "<script type='text/javascript'>window.location.replace('../');</script>";
}
else {
print("<script type='text/javascript'>document.getElementsByClassName('errors').innerHTML = '<h1 class='redback'>SORRY, BUT THIS ACCOUNT DOESN'T EXISTS</h1>';</script>");
}
}
?>
MY HTML PAGE
<body>
<div class="errors"></div>
<fieldset class="replacement">
<legend>LOGIN</legend>
<h1>LOGIN WITH YOUR INFORMATION</h1><br><br>
<form method="POST" action="<?php $_SERVER["php_self"]; ?>">
<input type="text" name="lusername" placeholder="YOUR USERNAME">
<input type="password" name="lpassword" placeholder="YOUR PASSWORD" class="password">
<br>
<br>
<label>KEEP ME LOGGED IN: </label>
<input type="checkbox" name="loggedin" checked>
<br><br>
<input type="submit" name="login" value="LOGIN"></form>
</fieldset>
</div>
</body>
</html>
When I am changing innerHTML of errors as described above, it doesn't changes. It says ; is missing in console or sometimes that errors is null. How can I fix it?
At the point you echo your javascript code, the html element with the id errors dont exists inside the dom. So the return of getElementById will always be undefined.
<script>document.getElementById("errors")...</script>
... some more html
<div id="errors"></div>
You could fix this by calling the javascript code after the dom document is ready. Using jQuery, you could do this this way
// event handler for document ready
$(function() {
// at this point, the dom is ready and the 'errors' id exists
$('#errors').html("some error message");
});
This would work, but seems a little bit unnecessary. The better way would be to just echo the actual error message with php and don't use javascript to do this.
$error = false;
if (mysqli_num_rows($data)>0) {
header('location: ../');
} else {
$error = '<h1 class="redback">SORRY, BUT THIS ACCOUNT DOESN\'T EXISTS</h1>';
}
and later
<div class="errors">
<?php if ($error) echo $error; ?>
</div>

Get data MySQL DB and display on in HTML

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
?>

onClick argument of php function

I've written the code below to set a variable in mysql to either 1 or 0. But somehow whenever i click the first button (1) it's always saving the 0-value assigned to the second button in the mysql table.
<head>
<?php
function update_ziekenwagen($Status) {
$servername = "localhost";
$username = "webapp";
$password = "password";
$dbname = "spoed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE AlgemeneVars SET value='".$Status."' WHERE id=4";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully:" . $Status;
//echo "UPDATE AlgemeneVars SET value=' " . $Status . " ' WHERE id=4";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();}
?>
</head>
<body>
<input type="button" value="Vertr" id="Vertr" name="Vertr" onclick="document.write('<?php update_ziekenwagen(1); ?>');" />
<input type="button" value="Terug" id="Terug" name="Terug" onclick="document.write('<?php update_ziekenwagen(0); ?>');" />
</body>
<head>
<?php
function update_ziekenwagen() {
$Status = $_POST['status'];
$servername = "localhost";
$username = "webapp";
$password = "sW7HwM225PxrwbZC";
$dbname = "spoed";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE AlgemeneVars SET value='".$Status."' WHERE id=4";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully:" . $Status;
//echo "UPDATE AlgemeneVars SET value=' " . $Status . " ' WHERE id=4";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
}
if (!empty($_POST)){
update_ziekenwagen();
}
?>
</head>
<body>
<form>
<input type="hidden" name="status" value="1" />
<input type="submit" />
</form>
<form>
<input type="hidden" name="status" value="0" />
<input type="submit" />
</form>
</body>
You can still make it work without using Ajax though using the above code. But this is NOT safe or good practice at all.

Load MySQL data into texboxes on button click

I have a webpage that needs to load data from a MySQL db into textboxes. So, the textboxes already exist and the values needs to be updated with those from the db. I have a JavaScript function for the button click, a PHP script to connect the db, but it doesn't seems to work. It just copies in the textboxes, but the value stored in the db.
Any idea what I do wrong?
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
...
</style>
<script>
//LOAD DATA
function btn_load_Click(){
document.getElementById('item1').value ="<?php echo $row['item1'];?>" ;
document.getElementById('item2').value ="<?php echo $row['item2'];?>" ;
document.getElementById('item3').value ="<?php echo $row['item3'];?>" ;
document.getElementById('item4').value ="<?php echo $row['item4'];?>" ;
}
</script>
</head>
<body>
<?php
$servername = "something.com.mysql";
$username = "myName";
$password = "xxxx";
$dbname = "myDB"
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn){
die("Connection failed:".mysqli_connect_error());
}
else {
$sql = "SELECT item1, item2, item3, item4 FROM myTable";
$result = mysqli_query($conn, $sql);
$row = mysql_fetch_array($result);
}
mysqli_close($conn);
?>
<form id="form1" style="width:500px;" method="post">
<div><button type="button" id="btn_load" onClick="btn_load_Click();" ></button></div>
<div id="MyItems">
<div><input id="item1" type="text" value=""/></div>
<div><input id="item2" type="text" value=""/></div>
<div><input id="item3" type="text" value=""/></div>
<div><input id="item4" type="text" value=""/></div>
</div>
</form>
</body>
</html>
First things first.
Don't mix mysql_* API with mysqli_*. This will give error and problems.
Better if you could use prepared statement, as mysql_* is already deprecated.
PHP and Javascript is different with one another. You can't just assign a PHP value to Javascript variable.
I'll teach you step by step on how to achieve your goals using jQuery.
First, you have to download jQuery here.
The trick we can do is to hide the row we have fetched from your query using hidden inputs. You are also mixing mysqli_* API with mysql_*, so this is wrong. I'll also introduce to you prepared statement.
$mysqli = new mysqli($servername, $username, $password, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* START PREPARING YOUR QUERY */
if($stmt = $con->prepare("SELECT item1, item2, item3, item4 FROM myTable")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($item1, $item2, $item3, $item4); /* STORE THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULTS */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
Then we can store the fetched data to these hidden inputs.
<input type="hidden" id="hid-item1" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item2" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item3" value="<?php echo $item1; ?>">
<input type="hidden" id="hid-item4" value="<?php echo $item1; ?>">
After that, we can now create a script, which will get the values from our hidden inputs and put it in your textboxes when the button is clicked.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script type="text/javascript">
$(document).ready(function(){ /* PREPARE YOUR SCRIPT */
$("#btn_load").click(function(){ /* WHEN THE BUTTON IS CLICKED */
/* GET THE VALUES OF THE HIDDEN INPUTS */
var hiditem1 = $("#hid-item1").val();
var hiditem2 = $("#hid-item2").val();
var hiditem3 = $("#hid-item3").val();
var hiditem4 = $("#hid-item4").val();
/* THEN PUT THEM INTO THE DESIGNATED TEXTBOXES */
$("#item1").val(hiditem1);
$("#item2").val(hiditem2);
$("#item3").val(hiditem3);
$("#item4").val(hiditem4);
});
});
</script>
You can also take a look at this jsfiddle for an example.

Categories