I have a web-based custom ticket sales I made for a friend and whenever I tried it (on any browser) it worked perfectly fine. However when it went live yesterday some people tried to book tickets and they would receive their email stating they had their seats booked (everything was ok) but the system would only record some of those seats.
Let's say that if they booked A1 - A10 they got an email saying they booked those but the system would only book A1 - A5 (or A6 or so, it seems random).
Also, this wouldn't happen with EVERY person it just happens randomly (at least I haven't found a proper reason for it to happen yet).
The code is here when I book the tickets:
$cantTotal=0;
$boletosF1 = $_POST['funcion1Hidden'];
if($boletosF1!=""){
$lugares = explode(" ", $boletosF1);
$cant = count($lugares);
$cantTotal += $cant;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func = explode(" ", $f1);
$cantUtilizados = count($func);
$repetidos = 0;
for ($int = 0; $int < $cant; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func[$r] == $lugares[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$boletosF2 = $_POST['funcion2Hidden'];
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
$cant2 = count($lugares2);
$cantTotal+=$cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados = count($func2);
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
$totalAPagar=120*$cantTotal;
and when I save them to the Database and send the email:
$boletosF1 = $_POST['boletosF1'];
$boletosF2 = $_POST['boletosF2'];
$nombre = $_POST['name'];
$correo = $_POST['mail'];
$cant1=0;
$cant2=0;
if($boletosF1!=""){
$lugares1 = explode(" ", $boletosF1);
echo $lugares1;
$cant1 = count($lugares1);
echo $cant1;
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
$func1 = explode(" ", $f1);
$cantUtilizados1 = count($func1);
$repetidos = 0;
for ($int = 0; $int < $cant1; $int++) {
for ($r = 0; $r < $cantUtilizados1; $r++) {
if ($func1[$r] == $lugares1[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
if($boletosF2!=""){
$lugares2 = explode(" ", $boletosF2);
echo $lugares2;
$cant2 = count($lugares2);
echo $cant2;
$f2 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$sqlPag2 = "SELECT * FROM pagados";
if ($resultPag2 = mysql_query($sqlPag2)) {
while ($rowPag2 = mysql_fetch_array($resultPag2)) {
$f = $rowPag2['funcion'];
$lugar = $rowPag2['lugar'];
$count++;
if ($f == "F2") {
$f2.= ( $lugar . " ");
}
}
}
$func2 = explode(" ", $f2);
$cantUtilizados2 = count($func2);
$repetidos = 0;
for ($int = 0; $int < $cant2; $int++) {
for ($r = 0; $r < $cantUtilizados2; $r++) {
if ($func2[$r] == $lugares2[$int]) {
$repetidos++;
}
}
}
if ($repetidos > 0) {
redirect("apartadoBoletos.php?error=1");
}
}
$rand = rand(0, 500);
$clave = sha1($rand . date("shd"));
$clave = substr($clave, 5, 5);
//insertar nuevo cliente
//mysql_query('BEGIN');
$sql = "INSERT INTO cliente(`idCliente`,`fecha`,`Nombre`,`correo`)VALUES('$clave',NOW(),'$nombre','$correo')";
$result = mysql_query($sql);
//crear arrays para guardar lugares
//insertar apartado F1
for ($i = 0; $i < $cant1; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares1[$i]','$clave','F1')";
$resultF1 = mysql_query($sqlF1);
}
for ($i = 0; $i < $cant2; $i++) {
$sqlF1 = "INSERT INTO apartados(`lugar`,`idCliente`,`funcion`)VALUES('$lugares2[$i]','$clave','F2')";
$resultF1 = mysql_query($sqlF1);
}
if (mysql_error ()) {
//echo mysql_error ();
// mysql_query('ROLLBACK');
redirect("apartadoBoletos.php?error=2");
} else {
$totalAPagar=($cant1+$cant2)*120;
// mysql_query('COMMIT');
$to = $correo;
$dia=date("d-m-Y");
//echo $dia;
//User info
$subject = "Boletos"; //The default subject. Will appear by default in all messages.
//The message to be received in the inbox
$msg .= "Estimad# $nombre: \n\n";
$msg .= "Clave: $clave " . "\r\n\n"; //the message itself
$msg .= "Boletos 28 de Junio: $boletosF1 " . "\r\n";
$msg .= "Boletos 27 de Junio: $boletosF2 " . "\r\n\n";
$msg .= "Total a pagar: $ $totalAPagar.00 " . "\r\n\n";
//$header .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$header .= "From: no-reply#booking.com" . "\r\n";
$header .= "Reply-To: no-reply#booking.com" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";
mail($to, $subject, $msg, $header);
}
function redirect($url) {
echo "<script language=\"JavaScript\"> window.location='$url'; </script>";
}
So far I can't find the error and I've got to since this should have started working yesterday but everything had to be stopped =/ I really need help here please.
Also, something that might help, I think the error could be related to the amount of users at a given time however since it just happens to some of the persons that use this I really can't say that's the reason.
If you aren't sure where the error is occurring, you could add extensive logging for a while to see if you can figure it out.
For example, when the user clicks save, or buy tickets, or whatever, you could write to the log file the data that the user has input on the form.
Then, you could log again when you send the purchase information to the database. Record the SQL or stored procedure name and parameter values.
This kind of extensive logging tends to hurt performance, but when you are in a desperate situation, sometimes it's worthwhile.
As soon as you have an idea of the problem, or think you have logged enough data to analyze, you can turn the logging back off.
This is really a comment, but it's too code centric to fit in one.
Consider rewriting your code so it actually uses SQL.
This code
$f1 = "";
$sqlAP = "SELECT * FROM apartados";
if ($resultAP = mysql_query($sqlAP)) {
while ($rowAP = mysql_fetch_array($resultApP)) {
$f = $rowAP['funcion'];
$lugar = $rowAP['lugar'];
$count++;
if ($f == "F1") {
$f1.= ( $lugar . " ");
}
}
}
Looks silly, you're not using SQL at all.
Rewrite it into this:
$sqlAP = "SELECT group_concat(lugar SEPARATOR ' ') as lugar
, count(*) as count1
FROM apartados WHERE funcion = 'F1'";
if ($resultAP = mysql_query($sqlAP)) {
$rowAP = mysql_fetch_array($result_AP);
$count = $rowAP['count1'];
$lugar = $rowAP['lugar'];
}
Much faster and much cleaner.
Related
I'm trying to return an array from MyArray function and use [0] to write2file and use [1] to populate pushover(myArray($jason)). I have tried fwrite($myfile, echo $txt[0]); but this fails and only writes the word 'Array' to the file instead of contents of array. I've looked at print_r and implode but no luck.
write2file(myArray($json));
compare2files('old_version.txt', 'new_version.txt');
if (compare2files('old_version.txt', 'new_version.txt') == 'false') {
pushover(implode("\n",myArray($json)[1]));
rename("new_version.txt", "old_version.txt");
}
function write2file($txt) {
$myfile = fopen("new_version.txt", "w") or die("Unable to open file!");
fwrite($myfile, implode("\n",$txt[0]));
fclose($myfile);
}
function compare2files($file1, $file2) {
$file3 = file_get_contents($file1);
$file4 = file_get_contents($file2);
if (strcmp($file3, $file4) !== 0) {
return 'false';
}
}
function myArray($arry) {
$selected = array(5,6,7,10,12,15,17,18,22,24);
foreach($arry as $key => $value) {
if (in_array($key, $selected) || empty($selected)) {
$result .= $value['name']. chr(10);
$xTime .= $value['name']. chr(10);
$length = count($value["color"]);
for ($i = 0; $i < $length; $i++) {
if($value['time'][$i] != "") {
if(preg_match('/#ff0000/', $value['color'][$i])) {
$value['color'][$i] = 'RED';
}
if(preg_match('/#ffff00/', $value['color'][$i])) {
$value['color'][$i] = 'YELLOW';
}
if(preg_match('/#006600/', $value['color'][$i])) {
$value['color'][$i] = 'GREEN (Mini Disaster)';
}
if(preg_match('/#9933cc/', $value['color'][$i])) {
$value['color'][$i] = 'PURPLE (Trauma ByPass)';
}
if(preg_match('/#ff6600/', $value['color'][$i])) {
$value['color'][$i] = 'ORANGE (ReRoute)';
}
$xTime .= ' ' . $value["color"][$i] . ' - ' . $value["time"][$i] . chr(10);
$xColor .= ' ' . $value["color"][$i] . chr(10);
$results[0] = $xTime;
$results[1] = $xColor;
}
}
}
}
return $results;
}
I need to search every word of an string in the database. If an word exist it needs to be highlighted. The current script works, but needs a lot of memory for my server. I don't know how i make it easier, but maybe do you?
<?php
$total_messages = $_POST['total'] - 1;
for($x = 0; $x <= $total_messages; $x++)
{
//Search highlights
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc())
{
//Vars for highlights
$highlight_txt = $row['value'];
$highlight_type = $row['type'];
$highlight_color = "black";
$highlight_title = null;
//If the text isnt empty
if($highlight_txt != null || $highlight_txt != "")
{
//Type highlights
if($highlight_type == "tree") //Tree type
{
$highlight_type = "18"; //Category number
$highlight_background = "pink"; //Background
if($row['option1'] != null)
{
$highlight_title = htmlentities($row['option1']);
}
}
else
{
$highlight_background = "yellow"; //Background
}
//Add highlight
$message = preg_replace("/\b($highlight_txt)\b/i", "<span class='bc_highlight' highlight-type='$highlight_type' highlight-value='$highlight_txt' style='background: $highlight_background; color: $highlight_color;' title=''>$highlight_txt</span>", $message);
}
}
echo $message; //Display the message
}
Why not doing something like this?
$messages = ["This is my message1","This is my message2"];
$highlights = [];
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc()) {
$highlights[$row["value"]] = [
"type" => $row["type"],
"color" => $row["color"]
];
}
$callback = function($matches) use ($highlights) {
$word = $matches[1];
if(isset($highlights[$word])) {
$highlight = $highlights[$word];
return sprintf('<span style="color:%s">%s</span>',$highlight["color"],$word);
} else {
return $word;
}
};
foreach($messages as &$message) {
$message = preg_replace_callback("/(\w+)/i",$message,$callback);
}
i have a module which executes two functions. the first filters and showsthe latest comments per category. the second one filters and shows the top commenters of all categories. i want to hack it in order to show the top commenters per category. for the first one there is in the backend the option to select category but for the top commenters there is not.
here is the code of the module. forgive me for its length.
class modK2CommentsHelper
{
public static function getLatestComments(&$params)
{
$mainframe = JFactory::getApplication();
$limit = $params->get('comments_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$cid = $params->get('category_id', NULL);
$jnow = JFactory::getDate();
$now = K2_JVERSION != '15' ? $jnow->toSql() : $jnow->toMySQL();
$nullDate = $db->getNullDate();
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
$query = "SELECT c.*, i.catid, i.title, i.alias, category.alias as catalias, category.name as categoryname
FROM #__k2_comments as c
LEFT JOIN #__k2_items as i ON i.id=c.itemID
LEFT JOIN #__k2_categories as category ON category.id=i.catid
WHERE i.published=1
AND ( i.publish_up = ".$db->Quote($nullDate)." OR i.publish_up <= ".$db->Quote($now)." )
AND ( i.publish_down = ".$db->Quote($nullDate)." OR i.publish_down >= ".$db->Quote($now)." )
AND i.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND i.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND i.access<={$aid} ";
}
$query .= " AND category.published=1 AND category.trash=0 ";
if (K2_JVERSION != '15')
{
$query .= " AND category.access IN(".implode(',', $user->getAuthorisedViewLevels()).") ";
}
else
{
$query .= " AND category.access<={$aid} ";
}
$query .= " AND c.published=1 ";
if ($params->get('catfilter'))
{
if (!is_null($cid))
{
if (is_array($cid))
{
JArrayHelper::toInteger($cid);
$query .= " AND i.catid IN(".implode(',', $cid).")";
}
else
{
$query .= " AND i.catid=".(int)$cid;
}
}
}
if (K2_JVERSION != '15')
{
if ($mainframe->getLanguageFilter())
{
$languageTag = JFactory::getLanguage()->getTag();
$query .= " AND category.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').") AND i.language IN (".$db->Quote($languageTag).", ".$db->Quote('*').")";
}
}
$query .= " ORDER BY c.commentDate DESC ";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
if (count($rows))
{
foreach ($rows as $row)
{
if ($params->get('commentDateFormat') == 'relative')
{
$config = JFactory::getConfig();
$now = new JDate();
if (K2_JVERSION == '30')
{
$tzoffset = new DateTimeZone(JFactory::getApplication()->getCfg('offset'));
$now->setTimezone($tzoffset);
}
else
{
$tzoffset = $config->getValue('config.offset');
$now->setOffset($tzoffset);
}
$created = new JDate($row->commentDate);
$diff = $now->toUnix() - $created->toUnix();
$dayDiff = floor($diff / 86400);
if ($dayDiff == 0)
{
if ($diff < 5)
{
$row->commentDate = JText::_('K2_JUST_NOW');
}
elseif ($diff < 60)
{
$row->commentDate = $diff.' '.JText::_('K2_SECONDS_AGO');
}
elseif ($diff < 120)
{
$row->commentDate = JText::_('K2_1_MINUTE_AGO');
}
elseif ($diff < 3600)
{
$row->commentDate = floor($diff / 60).' '.JText::_('K2_MINUTES_AGO');
}
elseif ($diff < 7200)
{
$row->commentDate = JText::_('K2_1_HOUR_AGO');
}
elseif ($diff < 86400)
{
$row->commentDate = floor($diff / 3600).' '.JText::_('K2_HOURS_AGO');
}
}
}
$row->commentText = K2HelperUtilities::wordLimit($row->commentText, $params->get('comments_word_limit'));
$row->commentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->commentText);
$row->itemLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($row->itemID.':'.urlencode($row->alias), $row->catid.':'.urlencode($row->catalias))));
$row->link = $row->itemLink."#comment{$row->id}";
$row->catLink = urldecode(JRoute::_(K2HelperRoute::getCategoryRoute($row->catid.':'.urlencode($row->catalias))));
if ($row->userID > 0)
{
$row->userLink = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
$getExistingUser = JFactory::getUser($row->userID);
$row->userUsername = $getExistingUser->username;
}
else
{
$row->userUsername = $row->userName;
}
// Switch between commenter name and username
if ($params->get('commenterName', 1) == 2)
$row->userName = $row->userUsername;
$row->userImage = '';
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
$comments[] = $row;
}
return $comments;
}
}
public static function getTopCommenters(&$params)
{
JTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'tables');
$limit = $params->get('commenters_limit', '5');
$user = JFactory::getUser();
$aid = $user->get('aid');
$db = JFactory::getDBO();
$query = "SELECT COUNT(id) as counter, userName, userID, commentEmail FROM #__k2_comments WHERE userID > 0 AND published = 1 GROUP BY userID ORDER BY counter DESC";
$db->setQuery($query, 0, $limit);
$rows = $db->loadObjectList();
$pattern = "#\b(https?://)?(([0-9a-zA-Z_!~*'().&=+$%-]+:)?[0-9a-zA-Z_!~*'().&=+$%-]+\#)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-zA-Z_!~*'()-]+\.)*([0-9a-zA-Z][0-9a-zA-Z-]{0,61})?[0-9a-zA-Z]\.[a-zA-Z]{2,6})(:[0-9]{1,4})?((/[0-9a-zA-Z_!~*'().;?:\#&=+$,%#-]+)*/?)#";
$model = K2Model::getInstance('Item', 'K2Model');
$componentParams = JComponentHelper::getParams('com_k2');
if (count($rows))
{
foreach ($rows as $row)
{
if ($row->counter > 0)
{
$row->link = JRoute::_(K2HelperRoute::getUserRoute($row->userID));
if ($params->get('commenterNameOrUsername', 1) == 2)
{
$getExistingUser = JFactory::getUser($row->userID);
$row->userName = $getExistingUser->username;
}
if ($params->get('commentAvatar'))
{
$row->userImage = K2HelperUtilities::getAvatar($row->userID, $row->commentEmail, $componentParams->get('commenterImgWidth'));
}
if ($params->get('commenterLatestComment'))
{
$query = "SELECT * FROM #__k2_comments WHERE userID = ".(int)$row->userID." AND published = 1 ORDER BY commentDate DESC";
$db->setQuery($query, 0, 1);
$comment = $db->loadObject();
$item = JTable::getInstance('K2Item', 'Table');
$item->load($comment->itemID);
$category = JTable::getInstance('K2Category', 'Table');
$category->load($item->catid);
$row->latestCommentText = $comment->commentText;
$row->latestCommentText = preg_replace($pattern, '<a target="_blank" rel="nofollow" href="\0">\0</a>', $row->latestCommentText);
$row->latestCommentLink = urldecode(JRoute::_(K2HelperRoute::getItemRoute($item->id.':'.urlencode($item->alias), $item->catid.':'.urlencode($category->alias))))."#comment{$comment->id}";
$row->latestCommentDate = $comment->commentDate;
}
$commenters[] = $row;
}
}
if (isset($commenters))
return $commenters;
}
}
}
every help is appreciated. thank you very much
I´m pretty much entirely new to PHP, so please bear with me.
I´m trying to build a website running on a cms called Core. I'm trying to make it so that the previous/next buttons cycle through tags rather than entries. Tags are stored in a database as core_tags. Each tag has it own tag_id, which is a number. I've tried changing the excisting code for thep previous/next buttons, but it keeps giving me 'Warning: mysql_fetch_array() expects parameter 1 to be resource, null given in /home/core/functions/get_entry.php on line 50'.'
Any help would be greatly appreciated.
Get_entry.php:
<?php
$b = $_SERVER['REQUEST_URI'];
if($entry) {
$b = substr($b,0,strrpos($b,"/")) . "/core/";
$id = $entry;
$isPerma = true;
} else {
$b = substr($b,0,mb_strrpos($b,"/core/")+6);
$id = $_REQUEST["id"];
}
$root = $_SERVER['DOCUMENT_ROOT'] . $b;
$http = "http://" . $_SERVER['HTTP_HOST'] . substr($b,0,strlen($b)-5);
require_once($root . "user/configuration.php");
require_once($root . "themes/".$theme."/configuration.php");
require_once($root . "functions/session.php");
if(is_numeric($id)) {
$type = "entry";
} else {
$type = "page";
}
$id = secure($id);
if($type == "page") {
$data = mysql_query("SELECT p.* FROM core_pages p WHERE p.page_title = \"$id\"");
$page_clicks = 0;
while($p = mysql_fetch_array($data)) {
$url = $p["page_url"];
$path = $root . "user/pages/" . $url;
$page_clicks = $p['hits']+1;
require($path);
}
mysql_query("UPDATE core_pages p SET
p.hits = $page_clicks
WHERE p.page_title = $id");
}
if($type == "entry") {
// queries the dbase
$data_tags = mysql_query("SELECT entry_id,entry_title FROM core_entries WHERE entry_show = 1 ORDER BY entry_position DESC") or die(mysql_error());
$navArr=array();
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
function array_next_previous($array, $value) {
$index = array_search($value,$array);
//if user clicked to view the very first entry
if($value == reset($array)){
$return['prev'] = end($array);
$return['next'] = $array[$index + 1];
//if user clicked to view the very last entry
}else if($value == end($array)){
$return['prev'] = $array[$index - 1];
reset($array);
$return['next'] = current($array);
}else{
$return['next'] = $array[$index + 1];
$return['prev'] = $array[$index - 1];
}
return $return;
}
$data = mysql_query("SELECT e.* FROM core_entries e WHERE e.entry_id = $id AND e.entry_show = 1");
$entry_clicks = 0;
if(#mysql_num_rows($data) < 1) {
die("Invalid id, no entry to be shown");
}
while($e = mysql_fetch_array($data)) {
$nextPrevProject = array_next_previous($navArr,$id);
$entry_id = $e['entry_id'];
$entry_title = $e['entry_title'];
// DATE
$t = $e["entry_date"];
$y = substr($t,0,4);
$m = substr($t,5,2);
$d = substr($t,8,2);
$entry_date = date($date_format,mktime(0,0,0,$m,$d,$y));
$entry_text = $e['entry_text'];
$entry_extra1 = $e['entry_extra1'];
$entry_extra2 = $e['entry_extra2'];
$entry_client = $e['entry_client'];
$entry_position = $e['entry_position'];
$entry_hits = $e['hits']+1;
$entry_new = $e['entry_new'];
if($entry_new == 1) {
$isNew = true;
} else {
$isNew = false;
}
if($nice_permalinks) {
$entry_perma = "$http".$entry_id;
} else {
$entry_perma = "$http"."?entry=$entry_id";
}
$data_e2t = #mysql_query("SELECT e2t.tag_id FROM core_entry2tag e2t WHERE e2t.entry_id = $entry_id");
$tag_str = "";
while($e2t = #mysql_fetch_array($data_e2t)) {
$tag_id = $e2t["tag_id"];
$data_tags = #mysql_query("SELECT t.tag_text FROM core_tags t WHERE t.tag_id = $tag_id");
while($t = #mysql_fetch_array($data_tags)) {
$tag_text = $t["tag_text"];
$tag_str = $tag_str . "<a class=\"tag-link\" name=\"tag".$tag_id."\" href=\"#tag-"._encode($tag_text)."\">".$tag_text."</a>".$separator_tags;
}
}
$entry_tags = substr($tag_str,0,strlen($tag_str)-strlen($separator_tags));
$layout_path = $root . "user/uploads/" . treat_string($entry_title) . "/layout.php";
if(is_file($layout_path) && (#filesize($layout_path) > 0)) {
require($layout_path);
} else {
require($theme_path . "parts/entry.php");
}
}
mysql_query("UPDATE core_entries e SET
e.hits = $entry_hits
WHERE e.entry_id = $id");
}
if($isPerma) {
echo "<a class=\"index-link\" href=\"$http\">back to index</a>";
}
?>
You have not defined $data_entries, before using it here:
while($tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC)){
array_push($navArr,$tmparray['entry_id']);
}
That is why you get the very descriptive error message.
Did you mean to use $data_tags?
Use: "SELECT p.* FROM core_pages p WHERE p.page_title = '".$id."'
Note: mysql_connect is not sql-injection save. If you use mysql_connect, change to PDO.
$data_entries is not defined on line 50, then mysql_fetch_array return an exception of null value given.
Try to change $tmparray = mysql_fetch_array($data_entries,MYSQL_ASSOC) to $tmparray = mysql_fetch_array($data_tags,MYSQL_ASSOC).
Hope this help!
I have this code for a search engine. I need to make linkable the results, only in the column name, but when I add the code ALL the colums turns as a link.
Here is how the results looks like now: http://postimg.org/image/59y36mih7/
I need to construct the link for the column name in this way:
http://www.mysite.com/id, (coma included)
Can you help me how to make the query to get the info from id column and make only the results from name column clickable? I´m quite lost.
<?php
$MySQLPassword = "*****";
$HostName = "***";
$UserName = "***";
$Database = "****";
mysql_connect($HostName,$UserName,$MySQLPassword)
or die("ERROR: Could not connect to database!");
mysql_select_db($Database) or die("cannot select db");
$default_sort = 'ID';
$allowed_order = array ('name','description');
if (!isset ($_GET['order']) ||
!in_array ($_GET['order'], $allowed_order)) {
$order = $default_sort;
} else {
$order = $_GET['order'];
}
if (isset($_GET['keyword'])) {
if(!$_GET['keyword']) {
die('<p>Please enter a search term.</p>');
}
/////////////////////////HERE IS THE BEGINING OF CODE WHERE I THINK SHOULD BE THE PROBLEM ////////////////////////////
$tables = 'reports';
$return_fields = 'name organizer_id no_pages publication_date price';
$check_fields = 'name description';
$query_text = $_GET['keyword'];
$clean_query_text =cleanQuery($query_text);
$newquery=bq_simple ($return_fields, $tables, $check_fields, $clean_query_text);
$newquery = $newquery . " ORDER BY $order;";
$result = mysql_query($newquery) or die(mysql_error());
$numrows = mysql_num_rows($result);
if ($numrows == 0) {
echo "<H4>No data to display!</H4>";
exit;
}
echo "<p>Your search '$query_text' returned ".$numrows. " results.</p>\n";
echo "<p>Click on the headings to sort.</p>\n";
$row = mysql_fetch_assoc ($result);
echo "<TABLE border=1>\n";
echo "<TR>\n";
foreach ($row as $heading=>$column) {
echo "<TD><b>";
if (in_array ($heading, $allowed_order)) {
echo "$heading";
} else {
echo $heading;
}
echo "</b></TD>\n";
}
echo "</TR>\n";
/* reset the $result set back to the first row and
* display the data */
mysql_data_seek ($result, 0);
while ($row = mysql_fetch_assoc ($result)) {
echo "<TR>\n";
foreach ($row as $column) {
echo "<TD><a href='http://mysite.com/(here should be the ID)'>$column</TD>\n";
}
echo "</TR>\n";
}
echo "</TABLE>\n";
}
////////////////////////FINISH OF THE CODE WITH PROBLEM ////////////////////////////
/* * * * * * * * * * * * * * F U N C T I O N S * * * * * * * * * * * */
function cleanQuery($string)
{
$string = trim($string);
$string = strip_tags($string); // remove any html/javascript.
if(get_magic_quotes_gpc()) // prevents duplicate backslashes
{
$string = stripslashes($string);
}
if (phpversion() >= '4.3.0')
{
$string = mysql_real_escape_string($string);
}
else
{
$string = mysql_escape_string($string);
}
return $string;
}
function bq_handle_shorthand($text) {
$text = preg_replace("/ \+/", " and ", $text);
$text = preg_replace("/ -/", " not ", $text);
return $text;
}
function bq_explode_respect_quotes($line) {
$quote_level = 0; #keep track if we are in or out of quote-space
$buffer = "";
for ($a = 0; $a < strlen($line); $a++) {
if ($line[$a] == "\"") {
$quote_level++;
if ($quote_level == 2) { $quote_level = 0; }
}
else {
if ($line[$a] == " " and $quote_level == 0) {
$buffer = $buffer . "~~~~"; #Hackish magic key
}
else {
$buffer = $buffer . $line[$a];
}
}
}
$buffer = str_replace("\\", "", $buffer);
$array = explode("~~~~", $buffer);
return $array;
}
function bq_make_subquery($fields, $word, $mode) {
if ($mode == "not") {
$back = " LIKE '%$word%'))";
}
else {
$back = " LIKE '%$word%')";
}
if ($mode == "not") {
$front = "(NOT (";
$glue = " LIKE '%$word%' AND ";
}
else {
$front = "(";
$glue = " LIKE '%$word%' AND ";
}
$text = str_replace(" ", $glue, $fields);
$text = $front . $text . $back;
return $text;
}
function bq_make_query($fields, $text) {
$text = strtolower($text);
$text = bq_handle_shorthand($text);
$wordarray = bq_explode_respect_quotes($text);
$buffer = "";
$output = "";
for ($i = 0; $i<count($wordarray); $i++) {
$word = $wordarray[$i];
if ($word == "and" or $word == "not" and $i > 0) {
if ($word == "not") {
$i++;
if ($i == 1) { #invalid sql syntax to prefix the first check with and/or/not
$buffer = bq_make_subquery($fields, $wordarray[$i], "not");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "not");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
else {
if ($word == "and") {
$i++;
if ($i == 1) {
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
}
}
}
else {
if ($i == 0) { # 0 instead of 1 here because there was no conditional word to skip and no $i++;
$buffer = bq_make_subquery($fields, $wordarray[$i], "");
}
else {
$buffer = " AND " . bq_make_subquery($fields, $wordarray[$i], "");
}
}
$output = $output . $buffer;
}
return $output;
}
function bq_simple ($return_fields, $tables, $check_fields, $query_text) {
$return_fields = str_replace(" ", ", ", $return_fields);
$tables = str_replace(" ", ", ", $tables);
$query = "SELECT $return_fields FROM $tables WHERE ";
$query = $query . bq_make_query($check_fields, $query_text);
#
# Uncomment to debug
#
return $query;
}
?>
I'm not going to dig through your code completely, but you should delete your ID column and whatever variable is being used for ID(such as $id) should be formatted like this where your name column is printed.
"<?PHP echo $name ?>"