I have a table consists of three columns :
id
author
message
Once the user clicks on the More Button the button passes the Count parameter to .load function. And then new data should display but it
displays a blank page.What am i doing wrong?
this is index.php:
<div id="comments">
<?php
$v=$db->prepare('select * from comments limit 2');
$v->execute();
$data=$v->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
</div>
<input type="submit" name="" id="submit" value="More">
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
var commentCount=2;
$('#submit').click(function(){
commentCount=commentCount+2;
$('#comments').load('loadComments.php',{count:commentCount});
});
});
</script>
this is loadComments.php:
<?php
$db=new PDO('mysql:host=localhost;dbname=ajax',"root","");
$newCount=$_POST['count'];
$ex=$db->prepare('select * from comments limit $newCount');
$ex->execute();
$data=$ex->fetchALL(PDO::FETCH_ASSOC);
foreach ($data as $row) {
echo "<div>".$row['author']."</div>";
echo "<div>".$row['message']."</div>";
echo "</br>";
}
?>
EDİT:
If I use this way everything is ok.
$v=$db->prepare('select * from comments limit 3');
But I have checked count parametre inside loadComment.php
echo $newCount;
and I am able to get the value Its funny
The issue is because of using Single quoted strings (as ') instead of Double quote strings (as ") - as #mrunion mention in the comments
In PHP when using ' the inner string is not being evaluate in contrast to the " mark. So the statement of 'select * from comments limit $newCount' is been sent as is and the $newCount is not been evaluate as 2 or what ever int it hold.
Full explanation about PHP quote can be found here
Related
How can i take the data to transfer it into another php file for some sql query function through json? The idea of this is there will show a table take from my sql table with a button every row for every task_id. For now, I want to test by clicking on a button of a random table row, i want to test to get the task_id replacing the hi text. To show that task_id has successfully convert into a format that json accept and print out as json text format.
i tried to echo the task_id to check the value but nothing happen, so what i need to do? How can I change the row data into something I can use for json?
With fetch? Or?
<?php
$sql = "SELECT * from task t
inner join tasktracking tt
$result = $conn -> query($sql);
while($result && $row = $result->fetch_object()){
echo "<tr>
<td>".$row->status."</td>
<td>
<button onclick='startProcess(".$row->task_id.")' type='submit' name='start' id='start'>start</button>
<button onclick='endProcess(".$row->task_id.")' type='submit' name='end' id='end'>end</button>
</td>
</tr>";
}
$conn->close();
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<p id="demo">hi</p>
<script>
function startProcess(){
<?php
echo task_id;
?>
var myObj, x;
myObj = {"name":task_id};
x = myObj.name;
document.getElementById("demo").innerHTML = x;
}
</script>
</tbody>
</table>
<div>
</div>
</div>
Please bear in mind, I'm very new to PHP. I've only started taking it this semester at my school.
Here's what I want to eventually do: I have a senior project where I'm building a computer repair system. In the repair MySQL table, I have a bunch of fields and one of them is CustomerID (so I know which customers had which repair). I want to have a drop drown of customer's names, and then when I click on it, some how attach that customer's ID to a variable so I can do an INSERT statement. In order to partially achieve this, I've done things in smaller parts. The small part I have working is when I select a dropdown value, it outputs it to the screen, but that's in the javascript function.
Here's my code:
<?PHP
include('session.php');
$db_name = "";
$mysql_username = "";
$mysql_password = "";
$mysql_server = "";
$mysqli = new mysqli($mysql_server, $mysql_username, $mysql_password,
$db_name);
$query = "SELECT custID, CONCAT(custFirstName, ' ', custLastName) as
Customer_Name FROM customer";
$result = mysqli_query($mysqli, $query);
echo "<select name ='names' id='myselect' onchange = \"myFunction()\">";
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
echo "</select>";
echo "<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id=\"demo\"></p>
<script>
function myFunction() {
var x = document.getElementById(\"myselect\").value;
document.getElementById(\"demo\").innerHTML = x;
}
</script>";
$content = "<script> document.write(x) </script>";
echo "<br> <br> The technician ID = $sTechID <br> <br> The customer ID = $content";
?>
I can output the ID to the screen with the Javascript function, but when I try to store "x" into a php variable, it doesn't work. In chrome, the inspector says that X is undefined.
A side note: I made a test file with this code and it worked:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
Because the above code worked, I don't understand why my bigger code is not working.
I understand that my code is a mess, but any help will be greatly appreciated. Thanks!
PHP is a back-end language and can't detect front-end events such as click, change, etc.
In your larger code, the value of x will only be defined once the event is fired(onchange), that's when the select input changes. Javascript works that way, but PHP doesn't. Once PHP sends a response the first time, its job is done.
This is when you will want to use forms or Ajax.
Using forms would be a good start.
Quick note, it's good practice to try to keep HTML, CSS and JS separate from PHP as much as possible.
...
$result = mysqli_query($mysqli, $query);
?>
<form method='post' action='insert.php' /> <!-- Link to php file to insert data to database -->
<select name ='names' id='myselect' onchange = "myFunction()">
<?php
while ($row = mysqli_fetch_array($result)){
echo "<option value = '" . $row['custID'] . "'>" . $row['Customer_Name'] . "
</option>";
}
?>
</select>
<input type="submit" value="submit" /> <!-- You will need a button to submit the data -->
</form>
<p>When you select a customer name, a function is triggered which
outputs the ID of the selected customer.</p>
<p id="demo"></p>
And now your insert.php file would look like:
<?php
// Get data from that was posted from the form
$customer_id = $_POST['names'];
// Now do whatever with the customer ID
echo $customer_id;
I think you need a better understanding of PHP in general. PHP is executed BEFORE the browser executes the html/js that you've echo'd to it. The reason this works:
<?PHP
echo "
<script>
var x = \"hello\"
</script>";
$content = "<script> document.write(x) </script>";
echo "$content <br> <br> $content";
?>
is because you are writing JS to the dom and it's being executed once your browser reads it. If you run a var_dump($content); you will see that what you have stored in that PHP variable is not the result of x but actually a literal string that contains the text "<script> document.write(x) </script>".
The line echo "$content <br> <br> $content"; prints "<script> document.write(x) </script> <br> <br> <script> document.write(x) </script>"; to the DOM, which in turn is run as JS in the browser.
If you want your drop down selection to do something in PHP I would suggest triggering a JS function on change of the drop down that in turn sends an AJAX request to a separate PHP file that does what you need to do there and returns it to your function. This way you can update the HTML without navigating to another PHP page.
I have a functioning foreach that I want to expand on. It's simple:
<ul>
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
echo '
<li>'.$newest_variable. '</li>';} }?>
</ul>
Let's say its html output is this:
<li>one</li>
<li>two</li>
<li>three</li>
I want to be able to get a specific variable ($newest_variable) and put it in $_SESSION or do other things, maybe alert it with javascript, etc, etc.
Question:
Is this possible with this structure? How could I get a specific variable $newest_variable?
For example, in the 2nd <li>, just get two and put into $_SESSION['result']
Any insight or direction is grealty appreciated.
<ul id="itemList">
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
echo '
<li>'.$newest_variable. '</li>';} }?>
</ul>
<script>
$('#itemList li').click(function() {
var index = $(this).index();
var text = $(this).text();
alert('Index is: ' + index + ' and text is ' + text);
});
</script>
Heres small code with JQuery, you can pass those variables to php with ajax and set as session, as well execute other functions you want :)
If you want to make an array of all the elements from the foreach, it's pretty simple:
<ul>
<?
$sql_find = "SELECT DISTINCT(column_chosen) as Sec FROM column_a WHERE column_chosen NOT LIKE '' ";
$get_var = mysqli_query($db, $sql_find);
while ($r=mysqli_fetch_assoc($find_var)){
foreach($r as $newest_variable) {
$newArray[] = $newest_variable; //Makes an array of all elements of the foreach
echo '
<li>'.$newest_variable. '</li>';
}
}
?>
</ul>
Now, the array $newArray will have all values of the foreach so that, for example, if you wanted the second element, you could use $newArray[1].
I'm working to try and establish a "safe" dynamic form using php/jquery. I am trying to figure out how to encode a query result in the URL, but also being able to display the query correctly in the browser. Ive tried wrapping a urlencode around the data in each of the for loops but it outputs the encoded data and disables the ability to populate the second drop down.
<!-- Populate First Dropdown -->
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=htmlentities($row["name"])?></option>
<?php endforeach ?>
</select>
<br />
<!-- Populate Second Dropdown -->
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<!-- Jquery to Populate second and Produce image -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#second-choice").change(function() {
var first = $("#first-choice").val();
var sec = $(this).val();
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
});
});
</script>
Here is the getter.php file I use to populate second drop down using above jquery:
$choice = $_GET['choice'];
$sth = $db->prepare("SELECT code FROM sets WHERE name='$choice'");
$sth->execute();
$choicecode = $sth->fetchColumn();
$stmt = $db->prepare("SELECT * FROM cards WHERE code='$choicecode'");
$stmt->execute();
$data2 = $stmt->fetchAll();
?>
<?php foreach ($data2 as $row): ?>
<option><?=$row["cardname"]?></option>
<?php endforeach ?>
Basically I want to encode the data that goes in the drop downs because they contain spaces and apostrophes. How can I still do this while at the same time output them correctly?
urlencode should be used when you're constructing the query parameters in a URL. When you're putting text into HTML, you should use htmlentities. Also, use the ID column as the value in your options.
<?php foreach ($data as $row): ?>
<option value="<?=$row["id"]?>"><?= htmlentities($row["name"]) ?></option>
<?php endforeach ?>
Also, you should use parametrized queries to prevent SQL injection and avoid other problems when constructing the query if it contains special characters:
$stmt = $db->prepare("SELECT * FROM cards
WHERE code = (SELECT code FROM sets WHERE id = :id)");
$stmt->execute(array(':id' => $_GET['choice']));
$data2 = $stmt->fetchAll();
I have a dropdown list of gender. I am getting the values from my table 'candidate' and in this table i have a field which is actually a foreign key to another table.
The field is gender_code_cde, and the table name is gender_code. Now gender_code contains 2 rows. and id and a description. Its structure is like:
1->Male
2->Female
Its being displayed in dropdown list. but I want to get the id 1 if male is selected and id 2 if female is selected. My code is below:
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
I am working in codeIgniter.
// this will alert value of dropdown whenever it will change
<script>
function getvalue(val)
{
alert(val);
}
</script>
<p>
<label for ="gender">Gender:</label>
<?php
$query = mysql_query("select * from gender_code"); // Run your query
echo '<select name="GENDER" id="Gender" onchange="getvalue(this.value)">'; // Open your drop down box
//Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query))
{
echo '<option value="'.$row['gender_cde'].'">'.$row['gender_dsc'].'</option>';
}
echo '</select>';
?>
</p>
In Javascript, you can get the value with native JS.
var e = document.getElementById("give-the-select-element-an-id");
var gender_cde = e.options[e.selectedIndex].value;
If, you want it back at the server, it will come in to PHP as $_GET['GENDER'] or $_POST['GENDER'] depending on if the form does a POST or a GET request.
If you are submitting a (POST) form and this is inside that form you can access the the value (id) from CodeIgniter's $_POST wrapper: $this->input->post('GENDER');. I don't use CodeIgniter so I could be wrong, but it will be located in your $_POST array from PHP.
If you just want to replicate the variable somewhere on the page you can just echo it. Or set via js/jQuery with document.getElementById('#something').value = value; or jQuery('#something').html(value);.
You should also change the following:
use a foreach in place of your while:
foreach ($query as $row) {
echo $row['gender_x'] . $row['gender_y'];
}
use the CodeIgniter SQL wrapper instead of depreciated PHP functions. The query part is $this->db->query('SELECT statement goes here');. You should look at your CodeIgniters' version documentation for a more in depth explanation.
EDIT: To make it a bit more clear, an example:
$query = $this->db->query('SELECT * FROM gender_code');
foreach ($query->result() as $row) {
echo '<option value="' . $row->gender_cde . '">' . $row->geneder_dsc . '</option>';
}
This is assuming you have setup the previous calls in CodeIgniter. Please see http://ellislab.com/codeigniter/user-guide/database/examples.html and you may wish to read http://ellislab.com/codeigniter/user-guide/