Load MySQL data into texboxes on button click - javascript

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.

Related

Locate the reasoning for NULL values between HTML and PHP

I am trying to figure out why the resulting values are...
NULL NULL string(4) "PEAR"
..on the page they are displayed on.
Originally I do not want them to be displayed but I want the php code to run, using local storage data, when the page loads, then possibly return a boolean value or something in that direction. With a set goal in mind, I am looking for the mistake I have made that creates the NULL values. I have the following code:
validateSession.php , php functionality that will validate values from localstorage and database
<?php
include("config.php");
include("refc/refcvalidation.php");
$sesuserid = $_POST[$valuserid];
$sessionid = $_POST[$valsesid];
var_dump($sesuserid, $sessionid);
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
var_dump("APPLES");
}else{
var_dump("PEAR");
}
?>
refcvalidation.php , reference coordination, ensuring same value on both pages
<?php
$valuserid = "VALSES1";
$valsesid = "VALSES2";
?>
homepage.php , basic page with contents
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
</script>
The values within HTML are set and have a value in the script section, they are null within the PHP $_POST[$valuserid]; and $_POST[$valsesid]; . Any ideas?
Have'nt tested this, but it might give you some ideas to a solution.
Maybe we could impolement some Ajax into this?
What is Ajax?
AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Ajax can give data as response.
refcvalidation.php
This should be removed
validateSession.php
<?php
include("config.php");
//include("refc/refcvalidation.php"); //REMOVED
$sesuserid = $_POST['valuserid'];
$sessionid = $_POST['valsesid'];
$conn = new mysqli($dbservername, $dbusername, $dbpassword, $dbname) or die($conn);
$stmt = $conn->prepare("SELECT * FROM sessiontable WHERE sesowner=? AND sescode=?");
$stmt->bind_param("is", $sesuserid, $sessionid);
$stmt->execute();
$result = $stmt->get_result();
$conn->close();
if ($result->num_rows > 0) {
$myObj->sesuserid = $sesuserid;
$myObj->sessionid = $sessionid;
$myJSON = json_encode($myObj);
echo $myJSON;
return true; //CONTAINS SOMETHING
}else{
return false; //CONTAINS NOTHING
}
?>
homepage.php
<?php
include("services/refc/refcvalidation.php");
include('services/validateSession.php');
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" href="general/styling.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="general/launch.js"></script>
</head>
<body>
<div id="topBox">
</div>
<div class="box">
<form id="logForm" action="validateSession.php" method="post">
<input type="hidden" required="required" name="<?php echo $valuserid ?>" id="userfield">
<input type="hidden" required="required" name="<?php echo $valsesid ?>" id="sesidfield">
</form>
</div>
</body>
<style>
</style>
</html>
<script>
$.ajax({
url: 'validateSession.php',
method: 'POST',
data: { valuserid: '<?php echo $valsesid ?>', valsesid: '<?php echo $valsesid ?>'},
success: function(data) {
var data_json= JSON.parse(data);
console.log(data_sjon);
localStorage.userid = data_json[0];
localStorage.sesidfield = data_json[1];
document.getElementById("userfield").value = localStorage.getItem("userid");
document.getElementById("sesidfield").value = localStorage.getItem("sessionid");
}
})
</script>

Adding Multiple Rows into Database

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')";
}

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>

preparing online test in php using javascript

I want to create a test pattern in PHP using MySQL database.Here i want to fetch questions form database and display those in my html pages. Now i want to create a division with next button and when user clicks it should display the next question that fetched from database in the same division dynamically. i guess it can be achieved through jQquery or javascript but unable to get the logic.
can anyone help.
thanks in advance.
here is a sample code that i have tried to display multiple divisions with javascript.
this is my database structure,
fields : qid,question,opt1,opt2,opt3,opt4
this is php code for fetching data form database.
<?php
$result=executeQuery("select * from quest");
if(mysql_num_rows($result)>0){
while($row=mysql_fetch_array($result)){
//echo $row['qid'];echo "<br/>";
echo $row['question']; echo "<br/>";
?>
<input type="radio" name="a1" value="'<?php echo $row['opt1']; ?>'" ><?php echo $row['opt1']; echo "<br/>"; ?>
<input type="radio" name="a1" value="'<?php echo $row['opt2']; ?>'" ><?php echo $row['opt2']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt3']; ?>'" ><?php echo $row['opt3']; echo "<br/>";?>
<input type="radio" name="a1" value="'<?php echo $row['opt4']; ?>'" ><?php echo $row['opt4']; echo "<br/>";?>
<?php
}
}
?>
<input type="submit" name="submit" value="submit">
now this fetches all the rows at a time and displays it.
this is javascript
var x=1;
function myfunc(){
document.getElementById(x).style.display="block" ;
x++;
}
when i click on button every time,respected division is displayed, but i want to display all data within one common division when each time the button is clicked.
If you don't want to reload a page when clicking the next button, we can use a Javascript library called jQuery.
I would also suggest that you use prepared statement rather than using the deprecated mysql_* API.
Lets start first by re-establishing your mysql_* and turn it to mysqli_*:
/* ESTABLISH CONNECTION */
$con = new mysqli("Host", "username", "password", "database"); /* REPLACE NECESSARY DATA INSIDE */
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest ORDER BY qid LIMIT 1")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close();
} /* END OF PREPARED STATEMENT */
After we get the data, we can now put it inside your form.
<h1 id="question"><?php echo $question; ?></h1>
<input type="hidden" id="qid" value="<?php echo $qid; ?>">
<input type="radio" name="a1" id="op1" value="<?php echo $opt1; ?>"><span id="op1text"><?php echo $opt1; ?></span><br/>
<input type="radio" name="a1" id="op2" value="<?php echo $opt2; ?>"><span id="op2text"><?php echo $opt2; ?></span><br/>
<input type="radio" name="a1" id="op3" value="<?php echo $opt3; ?>"><span id="op3text"><?php echo $opt3; ?></span><br/>
<input type="radio" name="a1" id="op4" value="<?php echo $opt4; ?>"><span id="op4text"><?php echo $opt4; ?></span><br/>
<input type="submit" name="submit" id="submit" value="Next"> <!-- THIS SERVES AS THE SUBMIT AND NEXT BUTTON -->
Before you proceed, download the library here.
Now, we can create a script that will take the answer and go to the next question. We will submit the answer of the user to the database using AJAX.
<script src="jquery-1.9.1.min.js"></script> <!-- REPLACE NECESSARY JQUERY FILE DEPENDING ON THE VERSION YOU HAVE DOWNLOADED -->
<script>
$(document).ready(function(){
$("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
var qid = $("#qid").val(); /* GET THE question id */
var selected = $("input[type='radio'][name='a1']:checked");
if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
answer = selected.val();
}
$.ajax({
type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
dataType : 'json',
success: function(result){ /* WHEN IT IS SUCCESSFUL */
/* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */
$("#qid").val(result.questionid);
$("#question").html(result.question);
$("#op1").val(result.op1);
$("#op2").val(result.op2);
$("#op3").val(result.op3);
$("#op4").val(result.op4);
$("#op1text").html(result.op1);
$("#op2text").html(result.op2);
$("#op3text").html(result.op3);
$("#op4text").html(result.op4);
}
}); /* END OF AJAX */
});
});
</script>
Then, we can create the action.php which takes the data/answer from the question page.
<?php
if(isset($_POST["questionid"])){
/* INCLUDE OUR NEW ESTABLISHED CONNECTION HERE */
/* PUT HERE YOUR INSERT QUERY WHICH STORES THE USER'S ANSWERS */
/* THEN FETCH THE NEXT QUESTION */
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM quest WHERE qid > ? ORDER BY qid LIMIT 1")){
$stmt->bind_param("i", $_POST["questionid"]);
$stmt->execute();
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4);
$stmt->fetch();
$stmt->close();
} /* END OF PREPARED STATEMENT */
/* THIS SET OF DATA WILL REPLACE THE DATA IN OUR CURRENT QUESTION PAGE */
echo json_encode(array("questionid" => $qid, "question" => $question, "op1" => $opt1, "op2" => $opt2, "op3" => $opt3, "op4", => op4));
} /* END OF ISSET */
?>
if you dont want to implement with ajax. Then list all questions and use jQuery to display single div. Use 'click' functions on next button to display the next questions.
If you are going by this method, try the following instruction. Hope It will be simple for you.
Display all the questions and answers.
while($row=mysql_fetch_array($result)){ ?>
<li class="test " id="qid_<?php echo $row['id']; ?>" >
<?php echo $row['question']; /* here display the stuff */ ?></li>
<?php }
Create "prev" and "next" buttons.
<span class="prev_q">Prev</span>
<span class="next_q">Next</span>
Add this css( to make first question as active )
li.test { display:none; }
li.activequestion{ display:block;background:#cccccc; color:#c40001; }
Add the script to make prev, next buttons working
<script>
jQuery(document).ready(function(){
jQuery('li.test:first').addClass('activequestion');
jQuery('.next_q').click(function(){
var nonext=jQuery('.test:last').hasClass('activequestion');
if(nonext)
{ alert("no next available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').next().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
jQuery('.prev_q').click(function(){
var noprevious=jQuery('.test:first').hasClass('activequestion');
if(noprevious)
{ alert("no previous available"); return false; }
var currentdiv=jQuery('.activequestion').attr('id');
jQuery('.test.activequestion').prev().addClass('activequestion');
jQuery('#'+currentdiv).removeClass('activequestion');
});
});
</script>

Categories