retrieve from database and send to another php file - php

I have 2 php files one that retrieve from database, other one take each value came from the database. the problem: data is being sent as whole not row by row. so I can not have each value seperatly. I am trying to find smart way to do so.
first file:
$host = 'localhost';
$user = 'root';
$pass = '';
$db_name="bbbb";
$conn = new mysqli($host, $user, $pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = array(); // create an array
while( $row = $result->fetch_assoc()) {
echo $row ['input']; //if my database have 2 rows one with value t1 and other with t2.
}
?>
second file:
<script src = "https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script>
$(document).ready(function(){
retrieveData();
});
function retrieveData(){
$.post('quick.php',{}, function(data){
window.alert(data);
});
}
</script>
the output i have is a single alert with (t1 t2)
my desire output to be 2 alerts window. first one with value t1 second with value t2.

try This:
use json to your server side,
while( $row = $result->fetch_assoc()) {
echo json_encode($row['input']);
}
and on your second file:
$.post('quick.php',{}, function(data){
window.alert(data);
},"json");

Related

ajax returns [object object]

i am making a quiz webapp with php and ajax where on click of radio button it triggers a function to get the new row in a database using ajax and php however it outputs object object inside the specified div element whenever the ajax success is called.
here is the ajax side of the code:
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var answer = $(this).val();
var question_id = $('#dataContainer').data('value');
$.ajax({
url:"quizengine.php",
method:"POST",
data:{
answer:answer,
question_id:question_id
},
dataType: 'json',
success:function(response){
console.info(response);
$('#question').text(response);
$('#answer_one').text(response);
$('#answer_two').text(response);
$('#answer_three').text(response);
}
});
});
});
</script>
and here is the php side of the code
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rubiqube";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
<?php
if (isset($_POST['answer'])) {
global $connection;
$answer = $_POST['answer'];
$question_id = $_POST['question_id'];
$result = mysqli_query($connection, "SELECT is_right FROM answers WHERE question_id='$question_id'");
$row = mysqli_fetch_assoc($result);
if (isset($row)) {
$correct = $row['is_right'];
if ($answer === $correct) {
$next = mysqli_query($connection, "SELECT Questions.question_id,Questions.lesson,Questions.instruction,Questions.question,Questions.image,Questions.option_type,Questions.question_value,Answers.answer_one,Answers.answer_two,Answers.answer_three,Answers.is_right FROM Questions LEFT JOIN Answers ON Questions.question_id = Answers.question_id WHERE Questions.question_id>'$question_id' ORDER BY Questions.question_id ASC LIMIT 1");
$nextrow = mysqli_fetch_assoc($next);
echo json_encode($nextrow);
exit();
}else{
echo "error";
exit();
}
}
}
?>
here is an image of what i am talking about
enter image description here
When the response comes back in the success callback, dataType: 'json' will convert it from json to an object (thus why you're seeing [object object]). You can't use the .text() method on it directly as that requires it to be a string. You may be able to do $('#question').text(response.key) depending on the data structure.
You need to simply either loop through the object and use the data, or access the properties directly (i.e. console.log(response.key)).
Here is some documentation from MDN on what to do with an object. Working with objects
Create an object of the Question on the server'side, then in your ajax response do this:
success:function(response){
$('#question').text(response.propertyName);
//propertyNamerefers to the one you made on the serverside
}

run a constant query against mysql using php without refreshing HTML page

Im looking at outputting mysql query results into a table on a php page where the 1st column of the table is the result and the 2nd column is populated with a Javascript timer
however my goal is to have it so that when data comes into the mysql database it display on the table and then when it stops being picked up by the query remove it from the table
the issue i face however is im not sure how to do this without resetting the javascript timer everytime the query is run,
I have gone through a couple of questions that have mentioned to use ajax and this would be fine but im not sure what i would put the HTML side
EDIT:
the below is now my second attempt code using ajax but i cant get the table to display it errors as unexpected token < line 27
my current page load Code to call the data is as followed:
PHP
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
# header('Content-Type: applicaton/json');
$sql = "SELECT
*
FROM
(SELECT
beacon,location,
COUNT(location) AS counter
FROM `track`
WHERE `date` = CURDATE() and `time` > NOW() - interval 60 second
GROUP BY beacon) AS SubQueryTable
ORDER BY beacon + 0 ASC;";
$result = $conn->query($sql);
$result = mysqli_query($conn , $sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
$conn->close();
?>
HTML
$.get('vendor/fetch.php', function(response) {
console.log(response);
var row;
response.forEach(function(item, index) {
console.log(item);
(unexpexted token here)
<table id="table">
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr style="background-color: <?php echo $row['item.location'];?>">
<td><?php echo $row['item.beacon'];?></td>
<td> <span class='minutes'>00</span>:<span class='seconds'>00</span>
</td>
</tr>
<?php }
mysqli_close($con);
?>
</table>
});
});
function updateTable() {
//console.log('function called');
$.get('vendor/fetch.php', function(response) {
response.forEach(function(item, index) {
console.log(item.beacon);
});
});
var updateTableInterval = setInterval(updateTable, 100);
};
</script>
</head>
<body>
<script>
var sec = 0;
function pad(val) {
return val > 9 ? val : "0" + val;
}
var timer = setInterval(function () {
$(".seconds").html(pad(++sec % 60));
$(".minutes").html(pad(parseInt(sec / 60, 10)));
}, 1000);
</script>
</body>

How to subtract from mysql database after pressing html button?

I am trying to subtract 0.05 from the cash amount of a player in my database once they push a button. Here is what I got so far.
My database:
Database name: accounts
Table: users
The Column I want to affect: cash_amount
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5ยข)</button>
Php file: (subtract5.php)
<?php
UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'
Thanks for helping, I am kind of a noob :)
This the following code, however dont exactly copy paste it, read the comments there are a few variables you might have to change and get from the database.
<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";
// Create connection
$userid = // You must enter the user's id here.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $previousAmount - 0.05;
$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Try executing that request. That's nothing more than a string without quotes around it. I'm sure that PHP considers it as an error.
You should consider learning PHP and MySQL before attempting to code a project.

How to limit checkbox selection in PHP?

So far I have been able to get data from MYSQL and display it as a checklist using PHP and HTML. Now I would like to limit the number of checkboxes that can be selected at a time. Javascript doesn't seem to be working with my PHP code.
EDIT: I've included my JScript below which is currently not workng. This JScript only works when I use it with manually created html checklists but not the one I have made below using MYSQL data. How can I fix my Javascript part so this works?
Here is my code:
<?php
$username = "root";
$password = "test";
$hostname = "localhost";
$dbname = "major_degrees";
$str='';
// Create connection
$conn = new mysqli($hostname, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT degree_name FROM majors";
$result = $conn->query($sql);
$out = '';
$cnt = 0;
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$cnt++;
$out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
}
echo $out;
}
$conn->close();
?>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<script>
$out.on("click", ":checkbox", function(event){
$(":checkbox:not(:checked)", this.form).prop("disabled", function(){
return $(this.form).find(":checkbox:checked").length == 2;
});
});
</script>
try this:
<script>
$(".someclass").change(function() {
var count = $(".someclass:checked").length; //get count of checked checkboxes
if (count > 3) {
alert("Only 3 options allowed..!");
$(this).prop('checked', false); // turn this one off
}
});
</script>

How can i pass the jquery value to php function

Here i want to call the php function with some parameter that will be held in some jquery function.
I have php function that takes one parameter and executes the sql query.
and also i have a jquery function where i am getting different values when select item from dropdown box.
now i want to pass the value of dropdown box to php function, how can i do this?
here is what i have done
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
});
php
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How can i do this?
Another way is to use Ajax like :
Jquery code:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
// here i want to pass this variable value to php function
-----------------------------------------------------
$.ajax({
url: 'newFunctionFile.php',
type: 'POST',
data: 'category='+category,
success: function(data) {
//you can add the code to show success message
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
});
and you have to create a file for php function let say file name is newFunctionFile.php as i have mention in ajax call:
if(isset($_POST['category'])) {
productManagement($_POST['category']);
}
function productManagement($procat){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT product_name,product_category,product_image_url FROM product_list where product_category='$procat'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["product_name"]."</td><td><a href=''><span class='glyphicon glyphicon-remove'></span>Remove</a></td><td><a href='edit-product.php'><span class='glyphicon glyphicon-edit'></span>Edit</a></td></tr>";
}
} else {
echo "No results found";
}
$conn->close();
}
How about something along these lines.
In your javascript:
$("#product_category").change(function(){
var category = $(this).val(); //getting dropdown value
location.href = location.href + "?val="+category; //reload the page with a parameter
});
And then in your PHP, add this code as your function call
if(isset($_GET['val'])) { //if 'val' parameter is set (i.e. is in the url)
productManagement($_GET['val']); //call function, with that parameter
}

Categories