There are two languages on my webpage. These are en and rs. ie english and russian. I want to be listed as en.php and rs.php under the languages directory, but only if they have the form url = ln = I, for example www.google.com/en or www.google.com/rs. For this I added the .htaccess file and the function.php file. but I do not know how to change the code I wrote below. How can I do that?
i have languages folder and en.php and tr.php
<?php
# Session başlat
session_start();
$available_langs = array('en','tr');
$_SESSION['lng']='en';
# Dil seçimi yapılmışsa
if($_GET['lng']) {
# Dil seçimini session'a ata.
$_SESSION['lng'] = $_GET['lng'];
# Anasayfa'ya yönlendir.
}
if ($_SESSION['lng'] == "en") {
$lng = "en";
}
elseif ($_SESSION['lng'] == "tr") {
$lng = "tr";
}
include 'languages/'.$lng.'.php';
include("fonksiyon.php");
?>
<li>
<?php
if(isset($_GET["lng"])){
if($_GET["lng"] == "tr"){
//echo 'EN';
echo ' <li style="float:left"> <a href="?lng=en"
style="border-left: solid gray 1px; line-height: 50%; margin-top: 15px; padding-right:2px; ">EN</a></li>';
} else if($_GET["lng"] == "en"){
// echo 'TR';
echo ' <li style="float:left"> <a href="?lng=tr"
style="border-left: solid gray 1px; line-height: 50%; margin-top: 15px; padding-right:2px; ">TR</a></li>';
} else {
echo 'no lang';
}
} else {
// echo 'TR';
echo ' <li style="float:left"> <a href="?lng=tr" style="border-left: solid gray 1px;
line-height: 50%; margin-top: 15px; padding-right:2px; ">TR</a></li>';
}
?>
</li>
.htaccess
RewriteEngine On
RewriteRule ^(.*)-(.*).html$ roportajdetay.php?id=$1&$baslik=$2 [L,NC]
fonksiyon.php
<?php function cevir($s) {
$tr = array('ş','Ş','ı','İ','ğ','Ğ','ü','Ü','ö','Ö','Ç','ç');
$eng = array('s','s','i','i','g','g','u','u','o','o','c','c');
$s = str_replace($tr,$eng,$s);
$s = strtolower($s);
$s = preg_replace('/&.+?;/', '', $s);
$s = preg_replace('/[^%a-z0-9 _-]/', '', $s);
$s = preg_replace('/s+/', '-', $s);
$s = preg_replace('|-+|', '-', $s);
$s = trim($s, '-');
return $s;
} ?> ?>
Related
I'm trying to upload an excel file to a mysql DB using PHP. I've got this working.
However, if I refresh the page or upload again another file, it gets duplicated.
I would like before it uploads a new file to clear (truncate) the table and then insert the new data.
Bue I cannot find where to put or how to put the TRUNCATE TABLE existencias_2018; if the Submit button is clicked and before it inserts the data.
Another issue is the refreshing thing. It is a way to stop the refresh after I've uploaded the data? Or a way that refreshing doesn't duplicate it?
So in summary the help i need is:
Where to put and how the TRUNCATE TABLE existencias_2018;.
Stop duplicating data if page gets refreshed.
Here is my piece of code:
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
$cup = "";
if(isset($Row[1])) {
$cup = mysqli_real_escape_string($conn,$Row[1]);
}
$color = "";
if(isset($Row[1])) {
$color = mysqli_real_escape_string($conn,$Row[2]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[3]);
}
$size36 = "";
if(isset($Row[1])) {
$size36 = mysqli_real_escape_string($conn,$Row[4]);
}
$size38 = "";
if(isset($Row[1])) {
$size38 = mysqli_real_escape_string($conn,$Row[5]);
}
$size40 = "";
if(isset($Row[1])) {
$size40 = mysqli_real_escape_string($conn,$Row[6]);
}
$size42 = "";
if(isset($Row[1])) {
$size42 = mysqli_real_escape_string($conn,$Row[7]);
}
$size44 = "";
if(isset($Row[1])) {
$size44 = mysqli_real_escape_string($conn,$Row[8]);
}
$size46 = "";
if(isset($Row[1])) {
$size46 = mysqli_real_escape_string($conn,$Row[9]);
}
$size48 = "";
if(isset($Row[1])) {
$size48 = mysqli_real_escape_string($conn,$Row[10]);
}
$size50 = "";
if(isset($Row[1])) {
$size50 = mysqli_real_escape_string($conn,$Row[11]);
}
$size52 = "";
if(isset($Row[1])) {
$size52 = mysqli_real_escape_string($conn,$Row[12]);
}
$size54 = "";
if(isset($Row[1])) {
$size54 = mysqli_real_escape_string($conn,$Row[13]);
}
if (!empty($model) || !empty($cup) || !empty($color) || !empty($description) || !empty($size36) || !empty($size38) || !empty($size40) || !empty($size42) || !empty($size44) || !empty($size46) || !empty($size48) || !empty($size50) || !empty($size52) || !empty($size54)) {
$query = "insert into existencias_2018(model,cup,color,description,size36,size38,size40,size42,size44,size46,size48,size50,size52,size54) values('".$model."','".$cup."','".$color."','".$description."','".$size36."','".$size38."','".$size40."','".$size42."','".$size44."','".$size46."','".$size48."','".$size50."','".$size52."','".$size54."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Datos de Excel importados en la base de datos satisfactoriamente";
} else {
$type = "error";
$message = "Ha habido un problema al importar los datos de Excel";
}
}
}
}
}else{
$type = "error";
$message = "Tipo de archivo invalido. Suba un archivo de Excel.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial;
width: 1000px;
}
.outer-container {
background: #F0F0F0;
border: #e0dfdf 1px solid;
padding: 40px 20px;
border-radius: 2px;
}
.btn-submit {
background: #333;
border: #1d1d1d 1px solid;
border-radius: 2px;
color: #f0f0f0;
cursor: pointer;
padding: 5px 20px;
font-size:0.9em;
}
.tutorial-table {
margin-top: 40px;
font-size: 0.8em;
border-collapse: collapse;
width: 100%;
}
.tutorial-table th {
background: #f0f0f0;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
.tutorial-table td {
background: #FFF;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
#response {
padding: 10px;
margin-top: 10px;
border-radius: 2px;
display:none;
}
.success {
background: #c7efd9;
border: #bbe2cd 1px solid;
}
.error {
background: #fbcfcf;
border: #f3c6c7 1px solid;
}
div#response.display-block {
display: block;
}
</style>
</head>
<body>
<h2>Importar existencias actualizadas</h2>
<div class="outer-container">
<form action="" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Buscar archivo Excel</label>
<input type="file" name="file" id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import" class="btn-submit">Importar</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM existencias_2018";
$result = mysqli_query($conn, $sqlSelect);
if (mysqli_num_rows($result) > 0){
?>
<table class='tutorial-table'>
<thead>
<tr>
<th>Modelo</th>
<th>Copa</th>
<th>Color</th>
<th>Descripcion</th>
<th>36</th>
<th>38</th>
<th>40</th>
<th>42</th>
<th>44</th>
<th>46</th>
<th>48</th>
<th>50</th>
<th>52</th>
<th>54</th>
</tr>
</thead>
<?php
$sql = "TRUNCATE TABLE existencias_2018";
while ($row = mysqli_fetch_array($result)) {
?>
<tbody>
<tr>
<td><?php echo $row['model']; ?></td>
<td><?php echo $row['cup']; ?></td>
<td><?php echo $row['color']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['size36']; ?></td>
<td><?php echo $row['size38']; ?></td>
<td><?php echo $row['size40']; ?></td>
<td><?php echo $row['size42']; ?></td>
<td><?php echo $row['size44']; ?></td>
<td><?php echo $row['size46']; ?></td>
<td><?php echo $row['size48']; ?></td>
<td><?php echo $row['size50']; ?></td>
<td><?php echo $row['size52']; ?></td>
<td><?php echo $row['size54']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
Is that what you want ?
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
// Looks like we have a correct file to upload.
// Let's TRUNCATE the table first :
$query = "TRUNCATE TABLE existencias_2018;";
mysqli_query($conn, $query);
// OK, table is empty, proceed with upload....
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
// and so on...
I'm currently creating a database / table list sort of system, where it will display the current likes/dislikes of a user. The likes/dislikes of a user is fetched, and managed by a function from a seperate file, called displayRating(). I use require_once to call the seperate file that it is located in, at the beginning of my list, then get down to business.
I then go ahead and have my
foreach(...){
...
displayRating($id);
...
}
However I'm getting an error, which seems to be telling me that I can't call a function multiple times within the same page. Here is my exact (unoptimized) code:
vote.php
<?php
function displayRating($id){
if(isset($id)){
require_once('medoo.min.php');
// Start up the D.B. Connection
$database = new medoo([
// required
'database_type' => 'mysql',
'database_name' => '****',
'server' => 'localhost',
'username' => '****',
'password' => '****',
'charset' => 'utf8',
// driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL
]]);
// xf_user_field_value DB. Amount of ratings: 506c617965725f7261746573 Current Score: 706c617965725f726174696e67
$accountinfo = $database->select('xf_user_field_value', ['field_value'], ["user_id"=>$id]);
$vScore = $accountinfo[5]['field_value'];
// Processing Time
$phrase = '<div class="bc"><div data-hint="%1$s" class="hint--right vote %2$s"></div></div>';
if($vScore == 0){
printf($phrase, 'Neutral Score', 'v_equal');
return;
} elseif ($vScore > 0){
// Positive Here
switch($vScore){
case 1:
printf($phrase, '1 Like', 'v_p1 hint--success');
break;
case 2:
printf($phrase, '2 Likes', 'v_p2 hint--success');
break;
case 3:
printf($phrase, '3 Likes', 'v_p3 hint--success');
break;
case 4:
printf($phrase, '4 Likes', 'v_p4 hint--success');
break;
case 5:
printf($phrase, '5 Likes', 'v_p5 hint--success');
break;
case 6:
printf($phrase, '6 Likes', 'v_p6 hint--success');
break;
case 7:
printf($phrase, '7 Likes', 'v_p7 hint--success');
break;
default:
printf($phrase, $vScore . ' Likes', 'v_p7 hint-success');
break;
}
} elseif ($vScore < 0){
// Negative Here
switch($vScore){
case -1:
printf($phrase, '1 Dislike', 'v_m1 hint--error');
break;
default:
if($vScore < -7){ $vClass = 7; } else { $vClass = abs($vScore); }
printf($phrase, abs($vScore) . ' Dislikes', 'v_m' . $vClass . ' hint--error');
}
}
} else {
return;
}
}
?>
displayCodes.php
<?php
function displayCodesMain($page){
if($page == 1){?>
<table class="friendcodes">
<tr>
<th>Username</th>
<th>Friend Code</th>
<th>Affinity</th>
<th>Level</th>
<th>Rating</th>
</tr>
<?php
$plisting = file_get_contents('plist.txt');
$plist = explode(' ', $plisting, 4);
require_once('vote.php');
array_pop($plist);
foreach($plist as $item) {
$item = explode(':', $item);
echo '<tr class="fc_premium">';
$item[3] = substr($item[3], 0, 3) . '-' . substr($item[3], 3, 7);
$item[1] = str_replace('&', ' ', $item[1]);
echo '<td>' . $item[1] . '</td><td>' . $item[3] . '</td><td style="text-transform:capitalize;">' . $item[4] . '</td><td>' . $item[5] . '</td><td> <div class="bc"><div class="vote v_p7"> </div></div> </td>';
echo '</tr>';
}
$listing = file_get_contents('list.txt');
$list = explode(' ', $listing, 26);
array_pop($list);
foreach($list as $item) {
$item = explode(':', $item);
echo '<tr class="fc_regular">';
$item[3] = substr($item[3], 0, 3) . '-' . substr($item[3], 3, 7);
$item[1] = str_replace('&', ' ', $item[1]);
echo '<td>' . $item[1] . '</td><td>' . $item[3] . '</td><td style="text-transform:capitalize;">' . $item[4] . '</td><td>' . $item[5] . '</td><td>'. displayRating($item[0]) .'</td>';
echo '</tr>';
}
echo '</table>';
} else if($page == 2) {
// Start page #2 management
?>
<table class="friendcodes">
<tr>
<th>Username</th>
<th>Friend Code</th>
<th>Affinity</th>
<th>Level</th>
</tr>
<?php
$listing = file_get_contents('list.txt');
$list = explode(' ', $listing, 51);
$list = array_slice($list, 25, 25);
array_pop($list);
foreach($list as $item) {
$item = explode(':', $item);
echo '<tr class="fc_regular">';
$item[3] = substr($item[3], 0, 3) . '-' . substr($item[3], 3, 7);
$item[1] = str_replace('&', ' ', $item[1]);
echo '<td>' . $item[1] . '</td><td>' . $item[3] . '</td><td style="text-transform:capitalize;">' . $item[4] . '</td><td>' . $item[5] . '</td>';
echo '</tr>';
}
?>
</table>
<?php
}
} // Close the function
?>
Test.php (What I'm using to dynamically get values and whatnot - warning, contains some CSS, which you can safely skip over.
<?php
/*include('newUser.php');
addNewUser('1', 'true', 'Spitfire', '8JX-UKR8', 'Spirit', '90');*/
require('displayCodes.php');
displayCodesMain(1);
?>
<head>
<style>
/*! Hint.css - v1.3.2 - 2014-05-18
* http://kushagragour.in/lab/hint/
* Copyright (c) 2014 Kushagra Gour; Licensed MIT */
.hint,[data-hint]{position:relative;display:inline-block}.hint:before,.hint:after,[data-hint]:before,[data-hint]:after{position:absolute;-webkit-transform:translate3d(0,0,0);-moz-transform:translate3d(0,0,0);transform:translate3d(0,0,0);visibility:hidden;opacity:0;z-index:1000000;pointer-events:none;-webkit-transition:.3s ease;-moz-transition:.3s ease;transition:.3s ease;-webkit-transition-delay:0ms;-moz-transition-delay:0ms;transition-delay:0ms}.hint:hover:before,.hint:hover:after,.hint:focus:before,.hint:focus:after,[data-hint]:hover:before,[data-hint]:hover:after,[data-hint]:focus:before,[data-hint]:focus:after{visibility:visible;opacity:1}.hint:hover:before,.hint:hover:after,[data-hint]:hover:before,[data-hint]:hover:after{-webkit-transition-delay:100ms;-moz-transition-delay:100ms;transition-delay:100ms}.hint:before,[data-hint]:before{content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1000001}.hint:after,[data-hint]:after{content:attr(data-hint);background:#383838;color:#fff;text-shadow:0 -1px 0 #000;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;box-shadow:4px 4px 8px rgba(0,0,0,.3)}.hint--top:before{border-top-color:#383838}.hint--bottom:before{border-bottom-color:#383838}.hint--left:before{border-left-color:#383838}.hint--right:before{border-right-color:#383838}.hint--top:before{margin-bottom:-12px}.hint--top:after{margin-left:-18px}.hint--top:before,.hint--top:after{bottom:100%;left:50%}.hint--top:hover:after,.hint--top:hover:before,.hint--top:focus:after,.hint--top:focus:before{-webkit-transform:translateY(-8px);-moz-transform:translateY(-8px);transform:translateY(-8px)}.hint--bottom:before{margin-top:-12px}.hint--bottom:after{margin-left:-18px}.hint--bottom:before,.hint--bottom:after{top:100%;left:50%}.hint--bottom:hover:after,.hint--bottom:hover:before,.hint--bottom:focus:after,.hint--bottom:focus:before{-webkit-transform:translateY(8px);-moz-transform:translateY(8px);transform:translateY(8px)}.hint--right:before{margin-left:-12px;margin-bottom:-6px}.hint--right:after{margin-bottom:-14px}.hint--right:before,.hint--right:after{left:100%;bottom:50%}.hint--right:hover:after,.hint--right:hover:before,.hint--right:focus:after,.hint--right:focus:before{-webkit-transform:translateX(8px);-moz-transform:translateX(8px);transform:translateX(8px)}.hint--left:before{margin-right:-12px;margin-bottom:-6px}.hint--left:after{margin-bottom:-14px}.hint--left:before,.hint--left:after{right:100%;bottom:50%}.hint--left:hover:after,.hint--left:hover:before,.hint--left:focus:after,.hint--left:focus:before{-webkit-transform:translateX(-8px);-moz-transform:translateX(-8px);transform:translateX(-8px)}.hint--error:after{background-color:#b34e4d;text-shadow:0 -1px 0 #592726}.hint--error.hint--top:before{border-top-color:#b34e4d}.hint--error.hint--bottom:before{border-bottom-color:#b34e4d}.hint--error.hint--left:before{border-left-color:#b34e4d}.hint--error.hint--right:before{border-right-color:#b34e4d}.hint--warning:after{background-color:#c09854;text-shadow:0 -1px 0 #6c5328}.hint--warning.hint--top:before{border-top-color:#c09854}.hint--warning.hint--bottom:before{border-bottom-color:#c09854}.hint--warning.hint--left:before{border-left-color:#c09854}.hint--warning.hint--right:before{border-right-color:#c09854}.hint--info:after{background-color:#3986ac;text-shadow:0 -1px 0 #193b4d}.hint--info.hint--top:before{border-top-color:#3986ac}.hint--info.hint--bottom:before{border-bottom-color:#3986ac}.hint--info.hint--left:before{border-left-color:#3986ac}.hint--info.hint--right:before{border-right-color:#3986ac}.hint--success:after{background-color:#458746;text-shadow:0 -1px 0 #1a321a}.hint--success.hint--top:before{border-top-color:#458746}.hint--success.hint--bottom:before{border-bottom-color:#458746}.hint--success.hint--left:before{border-left-color:#458746}.hint--success.hint--right:before{border-right-color:#458746}.hint--always:after,.hint--always:before{opacity:1;visibility:visible}.hint--always.hint--top:after,.hint--always.hint--top:before{-webkit-transform:translateY(-8px);-moz-transform:translateY(-8px);transform:translateY(-8px)}.hint--always.hint--bottom:after,.hint--always.hint--bottom:before{-webkit-transform:translateY(8px);-moz-transform:translateY(8px);transform:translateY(8px)}.hint--always.hint--left:after,.hint--always.hint--left:before{-webkit-transform:translateX(-8px);-moz-transform:translateX(-8px);transform:translateX(-8px)}.hint--always.hint--right:after,.hint--always.hint--right:before{-webkit-transform:translateX(8px);-moz-transform:translateX(8px);transform:translateX(8px)}.hint--rounded:after{border-radius:4px}.hint--no-animate:before,.hint--no-animate:after{-webkit-transition-duration:0ms;-moz-transition-duration:0ms;transition-duration:0ms}.hint--bounce:before,.hint--bounce:after{-webkit-transition:opacity .3s ease,visibility .3s ease,-webkit-transform .3s cubic-bezier(0.71,1.7,.77,1.24);-moz-transition:opacity .3s ease,visibility .3s ease,-moz-transform .3s cubic-bezier(0.71,1.7,.77,1.24);transition:opacity .3s ease,visibility .3s ease,transform .3s cubic-bezier(0.71,1.7,.77,1.24)}
.vote { background: url('vote.png') no-repeat top left; width: 20px; height: 20px; }
.vote.v_m7 { background-position: 0px 0px; }
.vote.v_p7 { background-position: 0px -30px; }
.vote.v_p6 { background-position: 0px -60px; }
.vote.v_m6 { background-position: 0px -90px; }
.vote.v_m5 { background-position: 0px -120px; }
.vote.v_p5 { background-position: 0px -150px; }
.vote.v_p4 { background-position: 0px -180px; }
.vote.v_m4 { background-position: 0px -210px; }
.vote.v_m3 { background-position: 0px -240px; }
.vote.v_p3 { background-position: 0px -270px; }
.vote.v_p2 { background-position: 0px -300px; }
.vote.v_m2 { background-position: 0px -330px; }
.vote.v_m1 { background-position: 0px -360px; }
.vote.v_p1 { background-position: 0px -390px; }
.vote.v_equal { background-position: 0px -420px; }
.bc {
display: inline-block;
width: 20px;
height: 20px;
padding: 1px;
border-radius: 12px;
border: 1px solid #888;
}
.friendcodes {
border-spacing: 0;
}
.friendcodes tr > td {
padding: 5px 25px;
}
.fc_premium {
background: #ffdf8e;
border-spacing: 0;
}
.fc_regular {
border-spacing: 0;
}
</style>
</head>
<body>
<h3>
Use form below for Adding IDs
</h3>
<form action="http://shortcutcentral.org/projects/friendcodes/receiveQuery.php" method="post">
<input type='text' value="481" name="id" /><br>
<input type="submit" />
</form>
<h3>
Current Testing Stuff
</h3>
<p>
<?php
require('vote.php');
displayRating(481);
?>
</p>
</body>
Here's the exact error for those of you who are keen on it - I've obfuscated some of the stuff here as well, since I am working from a live install:
Fatal error: Cannot redeclare displayRating() (previously declared in /home/**/public_html/**/vote.php:2) in /home/**/public_html/**/vote.php on line 68
Both displayCodes.php and test.php are requiring vote.php, and the later is not doing a require_once. Switch test.php to require_once('vote.php');
It seems that this is ocurring because in your test.php code you are including vote.php with
require('vote.php');
and also you are requiring 'displayCodes.php' in test.php
The problem here is that you also call 'displayCodes.php' inside vote.php so the function is being declared two times. Try commenting this line in test.php
require('displayCodes.php');
so that way you are just including the function once.
Hope this helps
Try to remove the require_once('medoo.min.php'); in displayRating() method. You're caling displayRating() to a loop so it probably iclude medoo.min.php many times.
I want make a pagination for my articles..
Here is class:
<?php
class Mynews {
public $conn;
public function __construct() {
$this->conn = mysqli_connect("localhost", "root", "", "mynews");
}
public function readAllarticles() {
$sql = "SELECT * FROM articles WHERE status='publish'";
$query = mysqli_query($this->conn, $sql);
return mysqli_fetch_all($query, MYSQLI_ASSOC);
}
}
$obj = new Mynews;
?>
display post: <?php
include('includes/crud.php');
foreach ($obj->readAllarticles() as $art) {
extract($art);
?>
<h3><?php echo $title; ?></h3>
<p>
<?php
$post = explode(" ", $content);
$slice = array_slice($post, 0, 10);
echo implode(" ", $slice), '...';
?>
</p>
<?php
}
?>
Now i want a function my class to make a pagination... and sorry for my bad eng.. :(
You use it:
<?php
class Pagination{
function Paginate($values,$per_page){
$total_values = count($values);
if(isset($_GET['page'])){
$current_page = $_GET['page'];
}else{
$current_page = 1;
}
$counts = ceil($total_values / $per_page);
$param1 = ($current_page - 1) * $per_page;
$this->data = array_slice($values,$param1,$per_page);
for($x=1; $x<= $counts; $x++){
$numbers[] = $x;
}
return $numbers;
}
function fetchResult(){
$resultsValues = $this->data;
return $resultsValues;
}
}
// Sample Usage
$pag = new Pagination();
$data = array("Hello","Rex","Prosper","Adrivan","Hehe");
$numbers = $pag->Paginate($data,2);
$result = $pag->fetchResult();
foreach($result as $r){
echo '<div>'.$r.'</div>';
}
foreach($numbers as $num){
echo ''.$num.'';
}
?>
I use this and it works for me
PHP
function pagination_one($webpage, $total_pages,$page){
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h=1;
if($page>$max_links){
$h=(($h+$page)-$max_links);
}
if($page>=1){
$max_links = $max_links+($page-1);
}
if($max_links>$total_pages){
$max_links=$total_pages+1;
}
echo '<div class="page_numbers">
<ul>';
if($page>"1"){
echo '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($total_pages!=1){
for ($i=$h;$i<$max_links;$i++){
if($i==$page){
echo '<li><a class="current">'.$i.'</a></li>';
}
else{
echo '<li>'.$i.' </li>';
}
}
}
if(($page >="1")&&($page!=$total_pages)){
echo '<li class="current">Next</li>
<li class="current">Last</li>';
}
echo '</ul> </div>';
}
function pagination_one($webpage, $total_pages,$page){
// Maximum number of links per page. If exceeded, google style pagination is generated
$max_links = 6;
$h=1;
if($page>$max_links){
$h=(($h+$page)-$max_links);
}
if($page>=1){
$max_links = $max_links+($page-1);
}
if($max_links>$total_pages){
$max_links=$total_pages+1;
}
echo '<div class="page_numbers">
<ul>';
if($page>"1"){
echo '<li class="current">First</li>
<li class="current">Prev</li> ';
}
if($total_pages!=1){
for ($i=$h;$i<$max_links;$i++){
if($i==$page){
echo '<li><a class="current">'.$i.'</a></li>';
}
else{
echo '<li>'.$i.' </li>';
}
}
}
if(($page >="1")&&($page!=$total_pages)){
echo '<li class="current">Next</li>
<li class="current">Last</li>';
}
echo '</ul> </div>';
}
// get the pagenum. If it doesn't exist, set it to 1
if(isset($_GET['pagenum']) ? $page = $_GET['pagenum']:$page = 1);
// set the number of entries to appear on the page
$entries_per_page = 6;
// total pages is rounded up to nearest integer
$total_pages = ceil($getresult/$entries_per_page);
// offset is used by SQL query in the LIMIT
$offset = (($page * $entries_per_page) - $entries_per_page);
$sql = "SELECT * FROM articles WHERE status='publish' LIMIT $offset,$entries_per_page";
// do your query results
pagination_one('articles.php', $total_pages,$page);
and CSS
.page_numbers {
width:100%;
background:#fff9f0;
overflow:hidden;
position:relative;
padding:50px 0;
}
.page_numbers ul, .pagenums ul {
clear:left;
float:left;
list-style:none;
margin:0;
padding:0;
position:relative;
left:50%;
text-align:center;
}
.page_numbers ul li,.pagenums ul li {
display:block;
float:left;
list-style:none;
margin:1px;
padding:0;
position:relative;
right:50%;
background: #a8a189;
width:25px;
}
.page_numbers ul li a, .pagenums ul li a {
display:block;
background: #fff;
border: 1px solid #a8a189;
padding:3px 6px;
text-decoration: none;
color: #7a7564;
font:bold 11px arial, verdana,sans-serif;
}
.page_numbers li.current,
.pagenums li.current{
width:50px;
}
.page_numbers a.current, .page_numbers li a:hover,
.pagenums a.current, .pagenums li a:hover {
background: #a8a189;
color: #fff;
}
So if a user enters [tag]hello[/tag] then it works great. However, if a user enters:
[tag]Hello
How are you[/tag]
with a line break in the form, the content between the [tag] [/tag] dose not get effected by the action. (.*?) is something missing here?
function tag($string) {
$rules = array(
'#\[tag](.*?)\[\/tag\]#i' => '<font style="color: #7c7c7c; font-style: italic;"> $1 <br><hr style="border-style: dotted; border-top: none; border-color: #9f9f9f;"></font>'
);
foreach ($rules as $link => $player)
$string = preg_replace($link, $player, $string);
return $string;
}
You can try this that worked for me:
<?php
//
function tag($string) {
$rules = array(
'#\[tag](.*?)\[\/tag\]#is' => '<font style="color: #7c7c7c; font-style: italic;"> $1 <br><hr style="border-style: dotted; border-top: none; border-color: #9f9f9f;"></font>'
);
foreach ($rules as $link => $player)
{
$string = preg_replace($link, $player, $string);
}
return $string;
}
//
// test 1:
//
$string = '[tag]Hello How are you[/tag]';
//
echo "<textarea style=\"width: 700px; height: 90px;\">"
. tag($string)
. "</textarea>";
//
// test 2:
//
$string = '[tag]Hello
How are you[/tag]
';
//
echo "<textarea style=\"width: 700px; height: 90px;\">"
. tag($string)
. "</textarea>";
?>
The modifiers 'is' are:
i: ignore case.
s: treat the text in single line mode.
my site which is a search engine returns many many results with a foreach loop as such:
foreach ($xml->channel->item as $result) {
$ltitle = $result->title;
$ldesc = $result->description;
$url = $result->displayUrl;
$link = $result->link;
if (strlen($ltitle) > 60)
{
$title = substr($ltitle,0,60).'...' ;
}
else
{
$title = $ltitle;
}
if (strlen($ldesc) > 195)
{
$desc = substr($ldesc,0,195).'...' ;
}
else
{
$desc = $ldesc;
}
echo "
<br>
<div class='resultbox'>
<a class='normal' style='text-decoration:none;font-size:huge;font-weight:bold' href='$link'>$title</a><br>
<div style='padding-top:3px;padding-bottom:4px;width:580px;'>
<font style='text-decoration:none;font-size:small;font-family:Arial;'>$desc<br></font></div>
<a style='text-decoration:none;' href='$link'><font style='text-decoration:none;font-size:small;color:green;font-weight:bold;'>$url<br></font></a>
</div>
";
}
And the resultbox class above styles all of the results with this
.resultbox
{
height:auto;
width:600px;
background-color:transparent;
font-size:19px;
padding:10px;
padding-left: 30px;
padding-right: 30px;
border-left: 6px solid #333;
}
.resultbox:hover
{
border-left: 8px solid #555;
}
The border-left color is what i want changed, i would like it to generate or to style randomly off of a list of colour codes so the results, insead of being all #333 can be #333 #555 #999 and so on..... any ideas?
If u have no problems using JS , You can certainly do this :
$(document).ready(function () {
$('.resultbox').mouseenter(function() {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
$('.resultbox').css("border-left", " 8px solid #"+randomColor);
});
});
change <div class='resultbox'> to <div class='resultbox random-color-".rand(1,YOUR_COLOR_LIMIT)."'> AND define colors like
.random-color-1 {
border-left: 8px solid #555;
}
.random-color-2 {
border-left: 8px solid #555;
}
.....
.random-color-YOUR_COLOR_LIMIT {
border-left: 8px solid #555;
}
change
<div class='resultbox'>
to
<div class='resultbox' style='border-left-color:$yourColorInCssFormat;'>
the style attribute overrides the css from class.
set $yourColorInCssFormat to the color you wish to have for the div. for example: $yourColorInCssFormat = '#999';
You can use inline style for that. Or alternatively you can user nth-child selector of css to repeat the border-color scheme something like this:
.resultbox:nth-child(n+1):hover {
}
.resultbox:nth-child(2n+1):hover {
}
.resultbox:nth-child(3n+1):hover {
}
First off, try this out for your foreachloop:
<?php foreach ($xml->channel->item as $result): ?>
<?php
$ltitle = $result->title;
$ldesc = $result->description;
$url = $result->displayUrl;
$link = $result->link;
if (strlen($ltitle) > 60){
$title = substr($ltitle,0,60).'...' ;
}else{$title = $ltitle;}
if (strlen($ldesc) > 195){
$desc = substr($ldesc,0,195).'...' ;
}else{$desc = $ldesc;}
?>
<div class='resultbox'>
<a class='normal' style='text-decoration:none;font-size:huge;font-weight:bold' href='<?php echo $link ?>'><?php echo $title; ?></a>
<br>
<div style='padding-top:3px;padding-bottom:4px;width:580px;'>
<font style='text-decoration:none;font-size:small;font-family:Arial;'>
<?php echo $desc; ?><br>
</font>
</div>
<a style='text-decoration:none;' href='<?php echo $link; ?>'><font style='text- decoration:none;font-size:small;color:green;font-weight:bold;'><?php echo $url; ?><br></font> </a>
<?php endforeach; ?>
That way you're not playing with big echos.
Now for generating random colors your could use php rand();
For example:
//Generate a random number between the two parameters
$randomNumber = rand(1, 3);
//Use this number to dictate what the variable color should be
if($randomNumber == 1){$color = "#333"}
elseif($randomNumber == 2){$color = "#555"}
elseif($randomNumber == 3){$color = "#999"}
You can then use the variable $color in your code to randomly assign one of the colors to elements.
Hope this helps!
-Gui