To give you an understanding of what I'm working on. I'm working on a project where on my school campus you can navigate around. For example a room can be called J2626 or J2617 etc... The thing is that when a user Is using my website I only want it to type in the exact name of the room to be able to display anything. Right now it doesn't work like I want it to.
For example: if you only type in J in the search field, it will display all rooms that start with J.
Here is my code right now:
<?php
$fileName = dirname(dirname(__FILE__)) . "../../db/bth_nav.sqlite";
if (isset($_GET['page'])) {
$argument = $_GET['page'];
$argument = "%" . $argument . "%";
$db = new PDO("sqlite:$fileName");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$stmt = $db->prepare('SELECT * FROM bth_nav WHERE name LIKE (:nameOwner) OR owner LIKE (:nameOwner);');
$stmt->execute(array($argument));
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (empty($res)) {
header("Location: " . "http://" . $_SERVER['index.php']);
}
?>
<div class = "formObjectSearch">
<?php foreach ($res as $val) { ?>
<div class = "infoTab">
<h2><?= $val['name']; ?></h2>
<p>Guidance: <?= $val['info']; ?></p>
<p>Whos sitting here?: <?= $val['owner']; ?>
</div>
<img class = "buildingImage" src = "img/<?= $val['image']; ?>"
<?php
}
}
?>
</div>
I've tried making diffrent if statements but with no success. So what I need help with is that I only want the user to be able to search for a correct room name and not be able to only search for J and display everything.
Update
Here is my index.php:
I used this link, because Code sample didn't want to work: index.php code
Here is my building.php:
Samer here: building.php code
And the the new search.php with help:
Same here: search.php code
I get these errors right now:
Notice: Undefined index: index.php in /path/incl/files/search.php on line 19
Warning: Cannot modify header information - headers already sent by (output started at /path/incl/header.php:7) in /path/incl/files/search.php on line 19
My header.php code:
Same here: header.php code
My config.php code:
Same here: config.php code
My footer.php code:
Same here: footer.php code
If i understanded you correctly and if you want to search for all rooms with starting letter J, you need to change your arguments.
Explanation:
'%J%' - searches for selected field, where is J letter.
'%J' - searches for selected field, where J is the last letter.
'J%' - searches for selected field, where J is the first letter.
Try to change your argument like that:
$argument = $argument . "%";
UPDATE
Fixing your if statement:
if (empty($res) OR $res == null) {
header('Location: http://'.$_SERVER['index.php']);
}
else {
echo '<div class = "formObjectSearch">';
foreach ($res as $val) {
echo '<div class = "infoTab">';
echo '<h2>'.$val["name"].'</h2>';
echo '<p>Guidance:'.$val["info"].'</p>';
echo '<p>Whos sitting here?:'.$val["owner"].'</p>';
echo '</div>';
echo '<img class="buildingImage" src="img/'.$val['image'].'" />';
}
echo '</div>';
}
OR
You can try to replace empty, with:
if ($res->rowCount() > 0) {
// if founded
} else {
// header('Location: http://'.$_SERVER['index.php']);
}
Related
I want to echo out this code but there's already open and close php tag , so how do I sub the html and php in the echo and make the php function works.
This is the code that I want to echo it out.
<div class="tutor-zoom-join-button-wrap">
<?php echo $browser_text; ?>
<?php _e('Join in Zoom App', 'tutor-pro'); ?>
</div>
This is the function that I made(replace with code above with 123)
<?php
$var1 = 1;
if ($var1 = 1) {
echo "123 ";
} else {
echo "The course ID, password and join button will only be shown before 30min of course start";
}
?>
This is what I try but not working
<?php
$var1 = 1;
if ($var1 = 1) {
echo
"<div class="tutor-zoom-join-button-wrap">"
"",.$browser_text."",
""._e('Join in Zoom App', 'tutor-pro')."",
"</div>",
"</div>" ;
} else {
echo "The course ID, password and join button will only be shown before 30min of course start";
}
?>
I have modified your code. Please check and you also refer to some PHP tutorials to learn php.
<?php
$var1 = 1;
if ($var1 == 1) {
echo
"<div class='tutor-zoom-join-button-wrap'>
<a href=" .$browser_url. " target='_blank' class='tutor-btn tutor-button-block'>".$browser_text."</a>,
<a href=".$meeting_data['join_url']."target='_blank' class='tutor-btn bordered-btn tutor-button-block'>"._e('Join in Zoom App', 'tutor-pro')."</a>",
"</div>",
"</div>" ;
}
else {
echo "The course ID, password and join button will only be shown before 30min of course start";
}
?>
The problem is in the long string you want to echo. The double quote " starts and ends the string. You have started and ended the string several times when what you want is one long string. If you want to use a double quotes inside the string you have to precede it with a slash \". To concatenate strings you need to use a dot .. Double quotes also allow you to place variables inside the string that will be replaced. So your echo statement could be done like this:
echo
"<div class=\"tutor-zoom-join-button-wrap\">" .
"$browser_text" .
"" . _e('Join in Zoom App', 'tutor-pro') . "" .
"</div>" .
"</div>" ; // Note that this tag does not appear to be necessary based on the code you have shown
You can write it like this:
<?php
$var1 = 1;
if ($var1 = 1) {
echo `<div class="tutor-zoom-join-button-wrap">
`.$browser_text.`
`._e('Join in Zoom App', 'tutor-pro').`
</div>
</div>` ;
} else {
echo "The course ID, password and join button will only be shown before 30min of course start";
};
?>
Hope It will work for you!
I'm currently working on a code that retrieves the first names and last names from a database and adds a link to other pages using an anchor link. This is the code:
<?php
$get_names_query_result = $get_names_query->get_result();
if (!$get_names_query_result) {
xecho("Names query failed.");
} else {
while ($name = $get_names_query_result->fetch_assoc()) {
?>
<?php xecho($name['first_name']) ?> <?php xecho($name['last_name']) ?>,
<?php
} // while fetch_assoc()
} // if $get_names_query_result
This code displays this on the webpage:
code-commas
I would like to eliminate that trailing comma at the end of the last element but I'm pretty lost on how to do it only for the name shown.
Any help would be much appreciated!
One approach I use is to create a variable, say $comma, and initialise it as "". Then after its first use, which adds nothing to your output, change it to ",". SO...
<?php
$comma = "";
$get_names_query_result = $get_names_query->get_result();
if (!$get_names_query_result) {
xecho("Names query failed.");
} else {
while ($name = $get_names_query_result->fetch_assoc()) {
?>
<?php echo $comma; ?> <?php xecho($name['first_name']) ?> <?php xecho($name['last_name']) ?>
<?php
$comma = ","
} // while fetch_assoc()
} // if $get_names_query_result
Note that the comma is now added before the anchor, not after it as you had it.
I already tried solving this problem with html array input name, it works on my sample but it doesn't during my implementation to my website.
This is my code for the Page.php
<form action = "POST" action = "Comments.php">
<?php
$x = 0;
while ($getRows = mysql_fetch_array($iQuer)){
echo "<input type = 'text' name = 'thes[ths][]' placeholder = 'Write a comment..'>
<a href = 'Comments.php?idy=".$_SESSION['ids']."&pageid=".$getRows['id']."&pagecount=".$x."'>";
$x++;
}
?>
</form>
Comments.php
<?php
session_start();
mysql_connect("127.0.0.1", "root", "toor");
mysql_select_db("matutorials");
$c = $_GET['pagecount'];
$d = $_POST['thes']['ths'][$c];
$a = $_GET['idy'];
$b = $_GET['pageid'];
echo $a ."<br>" . $b . "<br>";
echo $d;
?>
i do not have an idea if POST and GET is available/functioning at same time.
But according to my sample, it throws an error and searching for the undefined variable thes whenever i put $_GET superglobals on my another page where navigation happens.
This question already has answers here:
Fatal error: [] operator not supported for strings
(9 answers)
Closed 7 years ago.
I wrote (thanks to Stackoverflow help, too) a PHP script (called wunder_temp.php) which shows the temperature and location for a given number of Weatherunderground.com Stations.
I included this script in my footer, and it works well BUT on a single page.
If I open http://www.flapane.com/guestbook/guestbook.php the temperatures won't be shown in my footer, and error.log says:
[09-Sep-2012 09:46:45 UTC] PHP Fatal error: [] operator not supported for strings in /home/xxx/public_html/wunder_temp.php on line 47
$display = file($cachename, FILE_IGNORE_NEW_LINES); //ignore \n for non-reporting stations
foreach ($display as $key=>$value){
if($key % 2 == 0){
$temperature[] = $value; // EVEN (righe del file cache pari)
}else{
$location[] = $value; // ODD - **HERE IS LINE 47**
}
}
The weird thing is that guestbook.php is the ONLY page of my website where wunder_temp.php doesn't work.
What the above code does is reading the cachefile and put in a $temperature[] array the even lines and in $location[] array the odd lines.
Here's a sample from my cachefile:
26.8
Stadio San Paolo di Napoli, Napoli
24.4
Pozzuoli
Honestly I don't know why I see that errors just on my guestbook page.
It turns out that the "culprit" is the function loadmore.php which loads the guestbook comments (and which is included in guestbook.php) using a twitter-style ajax function. If I don't include it, wunder_temp.php works well, and it doesn't produce any error.
loadmore.php:
<div id='contcomment'>
<div class="timeline" id="updates">
<?php
$sql=mysql_query("select * from gbook_comments ORDER BY id DESC LIMIT 9");
while($row=mysql_fetch_array($sql))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
} ?>
</div>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
</div>
ajax_more.js AJAX twitter-style load-more-comments function:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('Nessun altro commento / No more comments');
}
return false;
});
});
ajax_more.php (needed by the above script):
<?
include "connect.php";
if(isSet($_POST['lastmsg']))
{
$lastmsg=$_POST['lastmsg'];
$lastmsg=mysql_real_escape_string($lastmsg);
$result=mysql_query("select * from gbook_comments where id<'$lastmsg' order by id desc limit 9");
$count=mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$msg_id=$row['id'];
$name=$row['name'];
$url=$row['url'];
$email=$row['email'];
$location=$row['location'];
$date= strtotime($row['dt']); //unix timestamp
$country_code=$row['country_code'];
$message=$row['body'];
$link_open = '';
$link_close = '';
if($url){
// If the person has entered a URL when adding a comment,
// define opening and closing hyperlink tags
$link_open = '<a href="'.$url.'" target="_blank" rel="nofollow">';
$link_close = '</a>';
}
// Needed for the default gravatar image:
$url_grav = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]).'/img/default_avatar.gif';
// Show flags
$image = strtolower($country_code) . ".png";
if (file_exists("./img/flags/" . $image)){
$show_image = true;
$image_link = "<img src='/guestbook/img/flags/$image' alt='user flag' />";
}else{
$show_image = false;
}
echo '<div class="comment">
<div class="avatar">
'.$link_open.'
<img src="http://www.gravatar.com/avatar/'.md5($email).'?size=50&default='.urlencode($url_grav).'" alt="gravatar icon" />
'.$link_close.'
</div>
<div class="name">'.$link_open.$name.$link_close.' </div><div class="location"><i>(da/from '.$location.' '.$image_link.' )</i></div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$date).'">'.date('d M Y',$date).'</div>
<p>'.$message.'</p>
</div>' ;
}
?>
<div id="more<?php echo $msg_id; ?>" class="morebox">
Carica Commenti più vecchi / Load older entries
</div>
<?php
}
?>
Any help is appreciated
$location is already a string on that page. This is why you properly initialize variables before you use them:
$temperature = $location = array();
foreach ($display as $key => $value){
if ($key % 2 == 0){
$temperature[] = $value;
} else {
$location[] = $value;
}
}
Even better, separate your variable scopes better so you don't get a name clash like that. Use functions and classes with their private variable scopes and don't put everything in the global scope.
It seems a matter of variable scope.
When you include loadmore.php in guestbook.php you are implicitly declaring $location as a string:
$location=$row['location'];
So this line of your loop:
$location[] = $value; // ODD - **HERE IS LINE 47**
is not implicitly declaring a new array variable on the first iteration but trying to append $value to the previously declared string variable, hence the error.
Try giving a different name to $location either in loadmore.php or guestbook.php or making loadmore.php a function (so it runs in its own scope) and then call it from your guestbook.php script after including its code on it. Or use explicit declaration of $location variable if you want to reuse it as an array (just add $location = array(); before the loop).
I think that loadmore.php and/or ajaxmore.php are setting a global variable ($location) to a string. When the guestbook page tries to index this variable you get the error.
Solution: use functions and local variables.
$location=$row['location']; is the issue. Because PHP doesn't have block level scope, you are essentially pre-setting this variable and trying to set it's array index using []. Because it's a string, that will break.
You should always initialize your variables to avoid these kinds of conflicts:
i.e.
$location = array();
Rename $location for one of the scripts. You have $location=$row['location'] somewhere. Also, declare the variable when using it as an array:
$array = array();
$array[] = 'item'; // when you add an item here, $array will always accept an array push.
I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).