i have a ads script which i stored in my database using textarea field. but when i echo that script in php. then it will not working.
this is my script which i saved in database by using textarea field.
<script type="text/javascript">
( function() {
if (window.CHITIKA === undefined) { window.CHITIKA = { 'units' : [] }; };
var unit = {"calltype":"async[2]","publisher":"seeknfameads","width":300,"height":250,"sid":"Chitika Default","color_site_link":"337ab7","color_text":"337ab7"};
var placement_id = window.CHITIKA.units.length;
window.CHITIKA.units.push(unit);
document.write('<div id="chitikaAdBlock-' + placement_id + '"></div>');
}());
</script>
<script type="text/javascript" src="//cdn.chitika.net/getads.js" async></script>
And when i fetch field and try to echo this. it is not working.
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$video_des=$row4['video_des'];
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
<script><?php echo $video_des;?></script>
}
please help to fix this problem.
As you are already inserting value of video_des with <script> and </script> tag
You don't need to add <script> tag again, Please try below.
$sql4 = "SELECT * FROM abc ORDER BY id DESC LIMIT 1";
$query4 = $conn->query($sql4);
$row4 = $query4->fetch(PDO::FETCH_ASSOC);
$video_des=$row4['video_des'];
$rowc = $query4->rowCount(PDO::FETCH_ASSOC);
if ($rowc>=1){
echo $video_des;
}
Simply do this at your if condition result
if ($rowc>=1){
echo $video_des; // remove script tag from here
}
Related
I fetched the data from my database and echoed it. Once I go to a prisoner's profile and his status is not = detained, the button 'Add Visitor' should be automatically disabled.
Where should I put my disable() function for it to be called?
Here's my script
<script language = "javascript" type = 'text/javascript'>
function disable(){
if(document.getElementById('prisonerstatus').value == "Detained"){
document.getElementById("visitorbtn").disabled= false;}
else{
document.getElementById("visitorbtn").disabled= true;
}
};
</script>
PHP
<?php
include "connect.php";
$idd =$_GET['id'];
$result = $connect->query("SELECT * FROM prisoner
INNER JOIN offensedata ON prisoner.prisoner_id = offensedata.prisoner_id
INNER JOIN arrestdata on prisoner.prisoner_id = arrestdata.prisoner_id
INNER JOIN booking ON prisoner.prisoner_id = booking.prisoner_id
WHERE prisoner.prisoner_id = $idd") or die($connect->error);
$rows1 = $result->fetch_all(MYSQLI_ASSOC);
foreach ($rows1 as $row){
$status = $row['status'];
echo "<input type = 'hidden' value = '$status' id = 'prisonerstatus'/>";
echo "<div class='col-lg-3'>Status: $status </div>";
}
Here's my button
<input type = "button" class="call_modal" style="cursor:pointer;margin-top:1%;" value = "Add Visitor" id = 'visitorbtn'>
Please excuse my code. This is for my school project only, these codes are what have been taught to us. I will study on how to avoid SQL injections and apply it soon. Thank you in advance :)
I have a mysql table with the name of a team in one column (club_name) and an id on another (club_id).
Every team has a logo named with their respective id .png.
Then I have a text input where the user can write the name of a team. There is a jQuery function that shows the possible team names found in the database according to what the user is typing so that it can autocomplete. Once the user selects one of the options the focus moves out of the text input. At this point, I would like the image to change to the logo corresponding to the team. When the text input is empty or the name does not match any team in the database the image should be 0.png
How can I achieve this? My code so far is below:
EDIT:
I have three problems right now:
The method suggested to store the club id in the json object is only
returning the first row of the table.
The method is below (although it only returns one row of the table it does work, the image changes to the appropriate one - I ran a little test by replacing 'thisclub' with the name of the club):
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
</script>
Using another method I was able to have all the rows in the json object but this one did not work when I ran the same test by replacing 'thisclub' with the name of one club):
<script>
var clublist = [
<?php
$clubid = array(); $clubname = array();
$search_clubs = mysql_query(" SELECT club_id, club_name FROM clubs ");
while($row = mysql_fetch_array($search_clubs)) {
$clubid[] = $row["club_id"]; // or smth like $row["video_title"] for title
$clubname[] = $row["club_name"];
}
$res = array($clubid, $clubname);
echo json_encode($res);
?>
];
</script>
The second problem is I don't know what to replace 'thisclub' with.
In other words, how to get the value returned by the function.
I am now using two vars - one to store the name of the clubs only, for the original function, the other one for the name of the clubs and respective id, for the function that makes the image change. This is because I don't know what changes to make in the original function so that it searches for the names in the new var (which contains club_id too)
The full code is below.
<img id="team-logo" src="logos/0.png"/>
<input type="text" class="club-name" name="home" autocomplete="off"/>
<script>
var clubs = [
<?php
$search_clubs = " SELECT club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
while($clubs = mysql_fetch_array($result_clubs)) {
$club_name = $clubs['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_assoc($result_clubs)); //only returns one row
?>
];
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
//$("#team-logo").attr("src", clubs+".png");
}
});
</script>
I would get the club_id from the original SELECT that you do.
Then on the focus out you can do something along the lines of:
$("#team-logo").attr("src", club_id+".png");
And that will set the image src to the new image.
Edit:
To expand a bit, storing the results of the sql query in a json object using json_encode() would allow you to use something like:
<script>
var clublist = [
<?php
$search_clubs = " SELECT club_id, club_name FROM clubs ";
$result_clubs = mysql_query($search_clubs);
echo json_encode(mysql_fetch_array($result_clubs));
?>
];
</script>
// Run the following code inside the focus.out section and set thisclub to the returned clubname
clubid = "";
$.each(clublist, function (i, elem) {
if (elem.club_name === thisclub) {
clubid = elem.club_id;
$("#team-logo").attr("src", clubid+".png");
}
});
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
Second Edit (Complete working example):
I've tested the following and I believe it includes everything you're looking for. The problem seemed to be in the formatting of the php array when passed to json encode. Pay close attention to the HTML changes.
$sql = " SELECT club_id, club_name FROM clubs ORDER BY club_id DESC";
$result_clubs = mysql_query($sql);
if (!$result_clubs) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
$clubs = array();
while($row = mysql_fetch_assoc($result_clubs)){
$clubs[] = array('club_id' => $row['club_id'], 'club_name' => $row['club_name']);
}
?>
<img id="team-logo" src="logos/0.png"/>
<input id="clubname" type="text" class="club-name" name="home" autocomplete="off"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript">
var clubs = [
<?php
foreach($clubs as $club) {
$club_name = $club['club_name'];
echo '"'.$club_name.'",';
}
?>
];
var clublist = <?php echo json_encode($clubs)?>; //only returns one row
$(".club-name").autocomplete({
source: clubs,
autoFocus: true,
minLength: 2,
delay: 0,
close: function(event, ui){
if (!event.keyCode || event.keyCode === 13){
$(this).parents('form').find('.club-name').filter(function (){
return $(this).val() === '';
}).first().focus();
//
}
clubid = "";
for(var i = 0; i < clublist.length; i++) {
obj = clublist[i];
if(obj.club_name == $("#clubname").val()){
clubid = obj.club_id;
$("#team-logo").attr("src", clubid+".png");
}
}
if(clubid == "") {
// show default image
$("#team-logo").attr("src", "0.png");
}
}
});
</script>
i'm making an online barcode scanner application and having some issues with sending a javascript variable to php for my query , and getting it back in my html file with the data.
User scans barcode (studentNr)
studentnr --> variable is going to be posted to the php file.
in php file : query to compare with variable
result of query --> back to the parameter of function(data)
print result.
Sounds easy, but how do I do this correctly?
Index.html :
<head>
<meta charset="utf-8" />
<!-- Set the viewport width to device width for mobile -->
<meta name="viewport" content="width=device-width" />
<script src="javascripts/jquery.js"></script>
</head>
<body>
<div>
<input type="text" name="barcode" id="barcode"> // BARCODE SCAN
<input type="text" id="student" placeholder="studentenNaam" size="30"> //NAME FROM DB
<!-- <input type="text" id="barcode" placeholder="Waiting for barcode scan..." size="40">
<input type="text" id="student" placeholder="studentenNaam" size="30">-->
</div>
// just the script for scanning the barcode :
<script>
var barcodeParsed = null;
var studentenNr = null;
$(document).ready(function() {
var pressed = false;
var chars = [];
$(window).keypress(function(e) {
if (e.which >= 48 && e.which <= 57) {
chars.push(String.fromCharCode(e.which));
}
console.log(e.which + ":" + chars.join("|"));
if (pressed == false) {
setTimeout(function(){
if (chars.length >= 10) {
var barcode = chars.join("");
console.log("Barcode Scanned: " + barcode);
barcodeParsed = barcode;
var barcodeParsing = barcodeParsed.substring(5,11);
$("#barcode").val("s" + barcodeParsing);
studentenNr = "s" + barcodeParsing;
}
chars = [];
pressed = false;
},500);
}
pressed = true;
});
});
$("#barcode").keypress(function(e){
if ( e.which === 13 ) {
console.log("Prevent form submit.");
$.post('testdb.php', {'studnr' :studentenNr}, function(data){ //POST JS VAR TO PHP FILE
$('#student').html(data); //RECEIVE DATA FROM DB INTO ID ELEMENT
});
e.preventDefault();
}
});
</script>
</body>
And in my testdb.php file it looks like this :
<?PHP
$studnr = htmlspecialchars($_POST['studnr']);
if(isset($studnr)){
$user_name = "root";
$password = "";
$database = "Student";
$hostname = "127.0.0.1";
$db_handle = mysql_connect($hostname, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);
if ($db_found) {
$SQL = "SELECT * FROM student where studentenNr= '$studnr'";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
/* Here needs the data to fetch*/
print $db_field['naam'] . "<BR>";
print $db_field['studentenNr'] . "<BR>";
print $db_field['voornaam'] . "<BR>";
}
mysql_close($db_handle);
}
else {
print "Database NOT Found ";
mysql_close($db_handle);
}
}
The problem is i can't receive any data from my html file in to my php file, plus i don't know how i can put the received data back in to my html file.
in the php-file..How do I write it back to the html ?
Do I need to use Ajax,Jquery,..
Any other solutions ?
Thank you for helping me out !
UPDATE
when adding this between the if(db_found) brackets I get an Internal Server Error 500.
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
$sql->execute($arraytest = array(':studnr' => studentenNr,naam );)
$sql->execute(array(":studentenNr" => $studnr));
$data = $sql->fetchAll();
foreach($item as $data){
print($item["naam"]);
log($item["naam"]);
On your javascript you're sending studnr parameter:
$.post('testdb.php', {'studnr' :studentenNr}, function(data){
In your php script you trying to get the value from studentenNr parameter:
$studnr = htmlspecialchars($_POST['studentenNr']);
You need to cahnge your script to
$studnr = htmlspecialchars($_POST['studnr']);
Edit:
You're getting internal error because of this line:
$sql = $db->prepare("select*from student where studentenNr= '$studnr' ");
You need to prepare the SQL statement with the parameters and then bind them, so the line should be (something like):
$sql = $db->prepare("select * from student where studentenNr= :studnr");
$sql->execute(array(':studnr' => $studnr ));
I want make data exist checker.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
?>
<script language="javascript" type="text/javascript">
var nick_exist = "<?php echo $nick_exist; ?>";
</script>
and this for $POST data
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function() {
if(nick_exist){
window.alert('Choose another nick please!');
}
});
I dont know where is the problem and my windows.alert is not running :(
thanks u
try like this get the count in php then return it to js:
NOTE: Please do not use mysql it is deprecated now start using mysqli or pdo.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
echo json_encode(array('count'=> $nick_exist));//send result to javascript
?>
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function(resp) {
var resp=JSON.parse(resp);
if(resp.count){
window.alert('Choose another nick please!');
}
});
I'm basically working on a site in which a user repeatedly clicks a button, increasing his score each time he clicks. I don't want the page to refresh between each click, so I'm using AJAX.
The problems I'm having currently are as follows:
When I try to set my javascript var to = <? echo $result['count']; ?>, it doesn't seem to work.
I don't understand how to correctly use PDO to UPDATE a MySQL table with a calculation in the query, such as $update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");. Is this the correct syntax for the calculation and is this the right way to do it in PDO?
Here is the code for my testing page which I am using for the clicking system:
<html>
<?php
$hostname = 'localhost';
$username2 = 'refrigerator';
$password = 'xxx';
$dbh = new PDO("mysql:host=$hostname;dbname=refrigerator", $username2, $password);
$username = $_COOKIE["user"];
$rows = $dbh->prepare("SELECT count FROM count WHERE username = '$username'");
$rows->execute();
$result = $rows->fetchALL();
$result['count'] = $count;
if(isset($_POST['action'])){
if ($_POST['action'] == 'increase'){
$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
}
}
?>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var count = <? echo $result['count']; ?>;
$("#update").click(function() {
$.ajax({
type: "POST",
url: "button.php",
data: {"action":"increase"},
success: function(update) {
count++;
$("#counter").html(+count);
}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"><? echo $result['count']; ?></div>
</body>
</html>
Thanks a lot, any help would be greatly appreciated. Even if you can point me in the right direction which will help me answer my questions, that would be awesome.
Thank you
You should have:
$count = $result['count'];
Instead of:
$result['count'] = $count;
The variable to the left of the = sign is what is receiving the assignment from whatever value is on the right of the = sign.
In your update statement you could, instead of using your count variable, could do:
$update = $dbh->execute("UPDATE count SET count=count+1 WHERE username='$username'");