Length of the values which is fetched from database - php

I need to find how many character each first name has and arrange from higher to lower. This code will print the id first name and last name using data table, I want to show the number of character each has in separate table with the corresponding first name.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/dt-1.10.15/datatables.min.css"/>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.15/js/dataTables.jqueryui.min.js"></script>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "name";
$conn = new mysqli($servername, $username, $password, $dbname);
if(mysqli_connect_errno($conn))
{
echo 'Failed to connect to database: '.mysqli_connect_error();
}
else{}
$sql="SELECT * FROM nametable";
$result=mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
echo "<table width=50% class='dataTable'><thead><tr><th>id</th><th>Firstname</th><th>Lastname</th></tr></thead><tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["firstName"]."</td><td>".$row["lastName"]."</td></tr>";
}
echo "</tbody></table>";
}
?>
<script>
$(document).ready(function() {
$(".dataTable").DataTable({
"lengthMenu": [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
"pagingType": "numbers"
} );
} );
</script>
<?php
$sql1="SELECT firstName, LEN(firstName) as LengthOfFirstName FROM nametable";
$result2=mysqli_query($conn, $sql1);
if ($result2->num_rows > 0){
while ($row2 = $result2->fetch_assoc()){
echo $row2 ."<br>";
}
}
?>
</body>
</html>

You seem to be looking for strlen, which returns the length of the input string:
strlen($row['firstName']);

Related

Can't call dynamic page with $_GET

I'm trying to use $_GET to call a dynamic page, but it throws "Error". Do I need to call page 1 from page 2 or why can't they talk to each other?
Thanks in advance for your help, supposingly there's an easy solution.
/Jimmy
This is page 1:
<!DOCTYPE html>
<html>
<head>
<title>Players</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<?php include ("header.php"); ?>
<?php
$servername = "localhost";
$username = "jim";
$password = "pass";
$dbname = "jim";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// SQL search
$sql = "SELECT PlayerID, Person FROM People where PlayerID is not null ORDER BY Person";
$result = $conn->query($sql);
// Condition
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Player</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>"."<a href='spelarfakta.php?=id{$row['PlayerID']}'>{$row['PlayerID']}</a>"."</td>"."<td>".$row["Person"]."</td>";
}
echo "</table>";
} else {
echo "No hits";
}
$conn->close();
?>
</body>
</html>
This is page 2:
<!DOCTYPE html>
<html>
<head>
<title>Player Stats</title>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<?php include ("header.php");
if (isset($_GET['id'])) {
echo '<p>'. $_GET['id'].'</p>';}
else {echo 'Error';
}
?>
</body>
</html>
Correct solution as a comment:
=id should be id=

find records in sql with same id as html button's id and generate a modal

The problem is that I have an html table with short info about employees that is taken from MySQL database. I'm trying to make a button with some ID that will open a modal window with full info about employee with the same value in it's field called 'ButtonID'. I tried to make desired query and set it to some variable in php and then access it in javascript but it didn't end well.
<!--
in <input id = "1" type="button" value="Full Info" input id equals to sql
'ButtonID' fields value
-->
Edit:
<form action="">
<input id = "1" type="button" value="Full Info"
onclick="fullInfo()">
</form>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Список сотрудников</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class = "header">
<img src = "img/header.png"></img>
</div>
<div class = "container">
<?php
echo "<table id='table_id' class = 'table table-striped'>";
echo "<thead>
<tr>
<th>№</th>
<th>ФИО</th>
<th>Имя транслитом</th>
<th>Дата рождения</th>
<th>Должность</th>
<th>Дата приёма</th>
<th>№ удостоверения</th>
<th>Полная информация</th>
</tr>
</thead>
";
class TableRows extends RecursiveIteratorIterator {
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td>" . parent::current(). "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "test";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT number, fullname, engname,birthdaydate, position, recruitmentDate,id,buttonid FROM employees");
$ids = $conn->prepare("SELECT * FROM employees");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
</div>
<div class = "footer">
<img src = "img/footer.jpg"></img>
</div>
<!--<link rel="stylesheet" type="text/css" href="css/styles.css">-->
<link rel="stylesheet" type="text/css" href="css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="css/normalize.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.15/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="//cdn.datatables.net/1.10.15/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function() {
$('#table_id').DataTable( {
"language": {
"url": "//cdn.datatables.net/plug-ins/1.10.13/i18n/Russian.json"
}
} );
} );
</script>
<!--
<script>
function fullInfo(){
var ids = <?php echo json_encode($ids); ?>;
for (int i = 0;i<ids.length;i++){
if (ids['buttonID'] == this.id){
alert ("good");
}
}
};
</script>
-->
</body>
</html>
You create a function that will process a call to your site like this:
http://my-site.com/employee.php?id=12
employee.php (idea)
$stmt = $conn->prepare("SELECT * FROM employees WHERE id=:id");
$stmt->execute(array(':id' => $_GET['id']));
$employee = $stmt->fetch(PDO::FETCH_ASSOC);
print "<ul>";
//list the employee data
foreach($employee as $key => $value)
{
$key = htmlspecialchars($key, ENT_QUOTES, 'UTF-8');
$value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8')
print "<li>". $key .': ' . $value . '</li>';
}
print "</ul>";
I suggest you to use an <a> tag instead of <button> as you have a link here, not a form. Just stylize it with CSS. In the column "Полная информация" of your table create a link:
<a target="_blank" href=\"/employee.php?id=$row['id']\">Полная информация</a>
This will open a new page. Process the request with PHP, I gave you the sample code.
Then add the ornaments like making the window modal, changing it's size etc.
For each row echo a button with its id as the employees id.
Add a letter before the id on the button to make sure it doesn't get repeated.
echo "<button id='emp*$employeeid*'>view</button>

Getting data from SQL to PHP

I have a data-table in mySQL and I need help accessing the information to display on an HTML Page.
Here are some details.
Host: 127.0.0.1:8889
username: root
password: root
database-name: gibsonek
table-name: events
Here is my code:
<html>
<head>
<meta charset="UTF-8">
<title>Gibson Ek Schedule</title>
<!--JQuery Add-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--My JS Add-->
<script src="script.js"></script>
<!--Normalize CSS Add-->
<link rel="stylesheet" href="css/normalize.css">
<!--Google Font - Open Sans - Add -->
<link rel='stylesheet prefetch' href='https://fonts.googleapis.com/css?family=Open+Sans:300,400,600'>
<!--Bootstrap Add-->
<link rel='stylesheet prefetch' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'>
<!--My CSS Add-->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="navbar">
<span>Gibson Ek Schedule</span>
</div>
<div class="header">
<div class="color-overlay">
<div class="day-number"></div>
<div class="date-right">
<div class="day-name"></div>
<div class="month"></div>
</div>
</div>
</div>
<div class="timeline">
<ul id = "l">
<?php
$connection = mysql_connect('127.0.0.1:8889', 'root', 'root');
mysql_select_db('gibsonek');
$query = "SELECT * FROM `events` WHERE 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo "<p>SQL DATA WILL GO IN HERE</p>";
}
mysql_close(); //Make sure to close out the database connection
?>
</ul>
</div>
</div>
</body>
</html>
Please use PDO (it's more flexible and safe)
$servername = "127.0.0.1:8889";
$username = "root";
$password = "root";
$dbname = "gibsonek";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM `events` WHERE id='1'");
$stmt->execute();
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll();
var_dump($result); // or as you like
There is a good article.
There is a best guide.
<div class="timeline">
<ul id = "l">
<?php
$host = "127.0.0.1:8889";
$username = "root";
$password = "root";
$db_name = "gibsonek";
$mysqli = new mysqli($host, $username, $password, $db_name);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '.$mysqli->connect_error);
}
$query = "SELECT * FROM `events` WHERE id='1'"; // Here if 1 means id
$result = $mysqli->query($query);
while($row = $result->fetch_assoc()) {
?>
<!-- Here You can add any HTML or css -->
<li><?php echo $row["column"]; ?> </li> // write your column name what you want to show
<?php
}
?>
</ul>
</div>
I think that would be clear for you, leave a comment if any query.
Thanks
I think you missed something
here is correct code:
<?php
$connection = mysql_connect('127.0.0.1:8889', 'root', 'root');
mysql_select_db('gibsonek');
$query = "SELECT * FROM `events` WHERE id(or any column as u want)='1'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
print_r($row);
}
mysql_close(); //Make sure to close out the database connection
?>

passing array to flot

I have been trying to make a graph plot with flot, and have ran into a problem.I Think the problem is with the way m using the php variable with flot Aside from that the graph isn't showing so I must have done something wrong. Below is the graph code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Flot Examples</title>
<link href="layout.css" rel="stylesheet" type="text/css">
<!--[if lte IE 8]><script language="javascript" type="text/javascript" src="../excanvas.min.js"></script><![endif]-->
<script language="javascript" type="text/javascript" src="./flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="./flot/jquery.flot.categories.js"></script>
</head>
<body>
<?php
//CONNECTING TO THE SERVER
$servername = "XXX";
$username = "YYY";
$password = "ZZZ";
conn = new mysqli($servername, $username, $password);
$sql = "SELECT NAME, AGE FROM pro_db";
$result = $conn->query($sql);
$wt=array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
//storing the values in the array
$wt[]=$row;//is this the right way
}
} else {
echo "0 results";
}
?>
<div id="placeholder" style="width:600px;height:300px;"></div>
<script type="text/javascript">
$(function () {
//accessing the array
var data = <?php echo $wt; ?>;
$.plot($("#placeholder"), [data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center" }
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
});
</script>
</body>
</html>``
Here's completely working example i made. If something doesn't work - there's some error with data. Try var_dump how your $wt array looks like in the end;
$data = [
['Andrew', 31],
['Helen', 29],
['Dasha', 24],
['Denis', 23]
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="canvas" style="width: 600px; height: 400px;"></div>
<script src="bower_components/jquery/dist/jquery.min.js"></script>
<script src="bower_components/flot/jquery.flot.js"></script>
<script src="bower_components/flot/jquery.flot.categories.js"></script>
<script>
var data = <?php echo json_encode($data) ?>;
$("#canvas").plot([data], {
series: {
bars: {
show: true,
barWidth: 0.6,
align: "center"
}
},
xaxis: {
mode: "categories",
tickLength: 0
}
});
</script>
</body>
</html>

jquery simple pager with first , last

<code>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery.pager.js Test</title>
<link href="Pager.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.pager.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#pager").pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PageClick });
});
PageClick = function(pageclickednumber) {
$("#pager").pager({ pagenumber: pageclickednumber, pagecount: 15, buttonClickCallback: PageClick });
$("#result").html("Clicked Page " + pageclickednumber);
}
</script>
</head>
<body>
$query = "select name from student";
$result = mysql_query(Query);
while($row=mysql_fetch_array($result)){
$student_name = $row['name'];
?>
<h1 id="result"><?php echo $student_name; ?></h1>
<? }
?>
<div id="pager" />
</body>
</html>
</code>
For my above code am not geting the student name , if i remove the pager script , the student name will appear, may i know , why, where i made mistake..
i thing i have to pass somthing to html() , but i am not sure..
while($row=mysql_fetch_array($result)){ $student_name = $row['name']; }
should be
$student_name = NULL;
while($row=mysql_fetch_array($result)){ $student_name .= $row['name']; }

Categories