i have a script (Users.php) that uses JSON_encode to display an array of objects in an HTML table.
as in:
Users.php :
html //empty table
script //fills the table by using json encode to get php array and display the contents in the table
myPhp.php :
gets info from database and creates the array.
my php file is working just fine and so is my script. the only problem is when i use JSON_encode to get the array from php to the script it shows an error
:
Uncaught SyntaxError: Unexpected token '<' //on line 1 of php code
my Users.php:
<body >
<!-- adding user -->
<form class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
<!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
<!-- table to display user info -->
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>
//display all users in table
var users = <?php echo JSON_encode($rows); ?>
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
}
}
</script>
</body>
my myPhp.php:
<?php
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
$rows[]=$row;
}
// Close connection
$result->close();
$sql->close();
?>
what I've tried:
I tried including the php file before using json_encode
<?php include'myPhp.php' ?>
var users = <?php echo json_encode($rows); ?>
this works when i run Users.php but if i add a user (by submitting the form in this webpage), add user file reads Users.php again after the user is added, users will end up not displaying and i will have the same error:
Uncaught SyntaxError: Unexpected token '<'
//in line 1 of myPhp.php
is there any other way to use JSON_encode that won't result in this error?
I'm not getting the same error that you are but MyUsers.php does not know about the variable you are trying to use:
//display all users
//users array contains names and roles
var users = <br />
<b>Warning</b>: Undefined variable $rows in <b>/var/www/html/public/temp/myUsers.php</b> on line <b>17</b><br />
null
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
}
}
There are a few different ways to get $rows in to myUsers.php.
One way that is easier to understand when you are learning is to do everything in one page: get your data at the top and render the HTML in the bottom.
MyUser2.php: I did not set up a database and hard coded the rows. Assuming that your database setup works you can removed the comments and the hard coded users. Note that since you are outputting a valid JSON array you do not have to re-parse it inside the javascript.
It will look like this in the browser:
//display all users
//users array contains names and roles
var users = ["user1","user2","user3"];
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
document.write(users[i] + '<br>');
}
}
MyUser2.php file listing:
<?php
/*
// fur UI Users.php
// calls all users from the db and displays them in users table
$sql = new mysqli("localhost","root","","atds");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$query = "SELECT * FROM users";
$result = $sql->query($query);
while($row = $result->fetch_object())
{
$rows[]=$row;
}
// Close connection
$result->close();
$sql->close();
*/
$rows[] = 'user1';
$rows[] = 'user2';
$rows[] = 'user3';
?>
<body >
<!-- adding user -->
<form class ="formArea" id = "addUser" action = "addUsers.php" method="POST">
<!-- addUsers.php will add users to the database then display Users.php again -->
</form>
<!-- display users -->
<table id="usersTable">
<!-- table to display user info -->
</table>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <!--jquery-->
<script>
//display all users
//users array contains names and roles
var users = <?php echo JSON_encode($rows); ?>;
displayUsers(users);
function displayUsers(users){
for(i = 0; i<users.length; i++)
{
//create table row
//add user information to the row
document.write(users[i] + '<br>');
}
}
</script>
</body>
This will get you started. A good framework for learning PHP is CodeIgniter. Laravel is a great framework and more popular but it adds a lot of magical stuff that makes regular PHP harder to learn.
In your "Users.php"
you should first include "myPhp.php"
<?php include'myPhp.php' ?>
and use it like this:
var json = '<?php echo JSON_encode($rows); ?>';
var users = JSON.parse(json);
solved.
the table was displaying correctly when i run Users.php but shows that error when adding a user by executing AddUsers.php which contains readfile('Users.php') at the end of it.
the problem was actually in readfile(Users.php)in addUsers.php.
readfile does not execute Users.php but only displays elements in it. therefore the JSON_encode never got executed and users weren't known to Users.php.
i solved this problem by changing readfile('Users.php') in addUsers to include 'Users.php';
Users.php code became :
<?php include 'displayUsers.php'; ?>;
var users = <?php echo JSON_encode($rows); ?>;
displayUsers(users);
function displayUsers(users){...}
Related
I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.
I have a problem and i can't find any solution on the internet.
So i have a db with about 20 columns. I print from this db only 5 columns for a preview like this:
<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db_test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT id,first,sec,school,data FROM test");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
After the table is print, I want when click is press to create a new page with all the records from the db for that specific id. I have search over the internet but i can't find any solution. Can anyone help me ?:) Thanks in advice.
I’ve take the liberty of making a few changes to the structure of the code to make it simpler.
The solution is to embed something in an anchor (a) which has a query string linking to the next page. Something of this nature:
details.php?id=…
Anyway, here is a solution:
$thead=array();
$tbody=array();
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
// Note: corrected an error which incorrectly imploded thead:
$thead=sprintf('<tr>%s</tr>',implode('',$all_property)); // implode & put into a proper row
// Get Data
while ($row = mysqli_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
And in the HTML after the PHP block:
<table class="">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>
</table>
Note the following points:
You shouldn’t put the logic into the HTML part of the document. Here I have just put the data into some variables to be output when the time comes. It’s cleaner and easier to maintain.
The recommend way to push onto an array is to use the $array[]=… notation.
I’m not sure why you are reading the column names if you already know that for your SQL query. However, I’ve left it that way.
I’ve also include suitable th elements and table sections.
That might work …
Basically you can play with hide() and show() using Jquery to achieve this. Initially you load all columns from the db and next you hide using some jquery functions. So on click the table again call jquery show method to display remaining columns
For that, use jQuery or other javascript supports. Basically redirect user to another page with "page?id=1". then extract id from url then use jQuery or js to load the corresponding values.
create a new page with empty form fields. then on load, get url parameter and use javascript to fill the fields.
<?php
$host = "localhost";
$user = "user";
$pass = "";
$db_name = "db";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
echo '<table class="data-table" border ="1">
<tr class="data-heading">'; //initialize table tag
$result = mysqli_query($connection,"SELECT id,firstname,lastname,email FROM test");
// Set Properties
$all_property = array('id','first','sec','school','data'); // ***
$thead=sprintf('<tr>%s</tr>',implode('',$thead)); // implode & put into a proper row
// Get Data
while ($row = mysql_fetch_array($result)) {
$tr=array();
foreach ($all_property as $item) {
// Here is a solution: Make id clickable
if($item=='id')
$tr[]=sprintf('<th>%s</th>',$item,$item);
else $tr[]=sprintf('<td>%s</td>');
}
$tbody[]=sprintf('<tr>%s</tr>',implode('',$tr));
}
?>
<table class="data-heading">
<thead>
<?php print $thead; ?>
</thead>
<tbody>
<?php print $tbody; ?>
<tbody>
I have seen some answers similar to this but they wont work for me.
I want to select data from a mysql database using mysqli / PHP and then pass the results to javascript.
I have the $conn stuff just above this, my code is at the very top of the file above the html, my script tags are in the body of the html. Is the correct place to have them? This just returns undefined, and if i try tweaking it i get unexpected < in index where i try and save it to the var ar. Or i can get unexpected ';' at the same line. Code shown below return unexpected ';'.
PHP
$query = "SELECT * FROM table";
$result = $conn->query($query);
while($row = $result->fetch_array())
{
$rows[] = $row;
}
$conn->close();
JavaScript
<script type="text/javascript">
var ar = <?php echo json_encode($rows)?>;
console.log(ar[0][0]);
</script>
I used to use this kind of code before like 1 year ago and it worked.
Now I got a problem with the php code when I fill my array with elements from the database I can't do the autocomplete, but when I comment the part where I get the code form the database and uncomment //$elements = array("25qt", "45tr", "az12"); than the autocomplete works.
It looks like the array is filled correctly from the database cause when I open the php file alone and do a var_dump($elements); i get the content of the array accordingly. Any idea why its not working when i fill the array from the db but it works if I use an array like $elements = array("25qt", "45tr", "az12");.
HTML code:
<input id="tegjithepjeset" type="text" class="form-control">
jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$("#tegjithepjeset").autocomplete({
source:'allParts.php',
minLength:1
});
});
</script>
Php code:
<?php
// An empty array:
$data = array();
// Create connection
include 'dbinfo.php';
$con=#mysqli_connect("$host","$user","$password","$db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$queryString = "SELECT code FROM ".$table;
$query =mysqli_query($con,$queryString);
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
$elements[]="".$rowDB[0];
}
//var_dump($elements);
//$elements = array("25qt", "45tr", "az12");
//Loop through the array to find matches:
foreach ($elements as $elm) {
// Add matches to the $data array:
if (stripos($elm, $_GET['term']) !== false) $data[] = $elm;//here we fill our empty array with values
} // End of FOREACH.
// Return the data:
echo json_encode($data);
?>
Replace the $elements array code as shown below.
$elements = array();
while($rowDB=mysqli_fetch_array($query)){
// $elements[]="".$rowDB[0];
$elements[]=$rowDB[0];
}
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>