onClick argument of php function - javascript

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.

Related

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

Getting Ajax error 500 when trying to post items from Database

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

Sort output from MySql with php

I try to return table values from Mysql db sorted
. I manage to connect and update the table right,
at the same page I wish to return the table back to html as chat history. just can't get the messages to show up sorted by time .
2) how is there a better way to return the output with ajax & jquery to the last div id messages?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sender = $_POST["sender"];
$receiver = $_POST["receiver"];
$message = $_POST["message"];
date_default_timezone_set('Asia/Tel_Aviv');
$create_date = date('Y-m-d H:i:s');
//Not sure this is right way to update the date.
if ($create_date != $update_date)
$date == $update_date;
$sql = "INSERT INTO messages (sender, receiver, message, create_date) VALUES ('$sender', '$receiver', '$message', '$create_date')";
if (mysqli_query($conn, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, sender, receiver, message, create_date FROM messages";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["id"]. ") " . $row["sender"]. " to " . $row["receiver"]. " : " . $row["message"]. " / " . $row["create_date"]."<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Html
<form action="" method="POST" enctype="multipart/form-data">
<p>name of sender:
<input class="input" name="sender" id="sender" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>name of receiver:
<input class="input" name="receiver" id="receiver" value="" size="13"
maxlength="13" dir="ltr" autocomplete="on" type="text" height="20" required><br>
<p>Message: <br>
<textarea name="message" id="message" value="" rows="5" cols="30" dir="ltr" required></textarea><br>
<input value="Submit" name="button" alt="submit" onsubmit="return checkForm(this);" border="0" type="submit" align="absmiddle"></p>
</form>
<P>MESSAGES</P>
<div id="messages">
<?php include_once("action.php") ?>
Javascript validation
(can't work )
I used required in html5 instead
function checkForm(form)
{
if($('#sender').val() == ''){
alert("Sender name can not be left blank");
form.sender.focus();
return false;
}
if($('#receiver').val() == ''){
alert("Receiver name can not be left blank");
form.receiver.focus();
return false;
}
if($('#message').val() == ''){
alert("Message input can not be left blank");
form.message.focus();
return false;
}
return true;
}
Maybe you can change your select query to
SELECT id, sender, receiver, message, create_date FROM messages ORDER BY create_date

There is an issue with Select in my SQL

The scoreboard has not been showing up in the rightHighScore div. It's just not showing anything. I'm making a high score board for my javascript snake game. So is there anything wrong with my MYSQL code here?
<html>
<link href='style.css' type='text/css' rel='stylesheet'>
<!-- Lets make a simple snake game -->
<canvas id="canvas" width="450" height="450" style="border:1px solid #000000;"></canvas>
<!-- Jquery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript">
</script>
<script src="snake.js" type="text/javascript"></script>
<?php $score = "<script>document.write(score)</script>"?>
<p id = 'demo'>Your Final Score: <script>score</script></p>
<div id = 'right'>
<div id = 'rightForm'>
<form action="highscoreregistry.php" method="post">
<input type="hidden" name="score" id="score">
</form>
</div>
<div id = 'rightHighScore' style = 'size:9px;'>
<?php
$servername = "-";
$username = "-";
$password = "-";
$dbname = "-";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Score, Date FROM snakehiscore";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["Name"]."</td><td>".$row["Score"]." ".$row["Date"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</div>
</div>
</html>
Add a semicolon to the query! So:
$sql = "SELECT Name, Score, Date FROM snakehiscore;";
2.Instead of using this:
$result = $conn->query($sql);
try this if you have mysqli installed:
$result = mysqli_query($conn, $sql);
mysqli_num_rows($result) > 0

Categories