At the moment I have a text area where people can insert their own sql scripts for people to see however it currently displays quite bland.
I was wondering if there was a way in which using Jquery/Javascript/PHP that when people load a note from the database, it then does a check through a list of words. For example "SELECT", "FROM", "WHERE", "INNER", "JOIN" and if they match it sets the colour of them to a defined colour?
This would need to happen when the note is displayed on the screen as the text is coming from a database. So maybe there is some way to check the words as they are pulled through from the database.
These notes are being pulled through as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
$stmt = sqlsrv_query($conn, $showNoteInfo);
}
if (isset($_POST['noteid']))
{
if (empty($_POST['noteid']))
{
$notes = 'No Data';
}
if (sqlsrv_has_rows($stmt))
{
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
echo "<div class='custom-font title-container'>
<div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
<div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editGeneralNote()'> </div>" . "<div data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>" . " <div class='save-note fa fa-thumbs-up' onclick='saveGeneralNote(); submitNoteText();'></div></div>
</div>";
echo "<textarea spellcheck='false' readonly id='ta1'>" . $data['Note'] . "</textarea>";
}
else
{
echo "No data found";
}
}
So how can I colour certain words pulled through from a database as they are displayed on screen?
If anyone could help I would appreciate it.
Good old way :
//Your keywords to be highlighted
$keyWord = array("SELECT", "FROM", "WHERE");
//The string to stlylish
$str = "Select * From db";
foreach(explode(" ", $str) as $word)
{
if (in_array(strtoupper($word), $keyWord))
{
echo '<span class="color">' . $word . '</span>';
}
}
If you prefer to get the result of the stylish process as a string and not a simple echo. You could use implode. It's the oposite of explode. You will just have to store the echo line in an array and implode the array after the loop.Resulting in somethink like this :
//Your keywords to be highlighted
$keyWord = array("SELECT", "FROM", "WHERE");
//The string to stlylish
$str = "Select * From db";
$result = array();
foreach(explode(" ", $str) as $word)
{
if (in_array(strtoupper($word), $keyWord))
{
array_push($result, '<span class="color">' . $word . '</span>');
}
else {
array_push($result, $word);
}
}
$str = implode($result, " ");
echo $str;
I would do it with preg_replace():
$note = preg_replace('%(SELECT|FROM|WHERE)%m', '<span style="color: green;">$1</span>', $data['Note']);
echo $note;
$1 references the first capturing group. More information about regular expressions in PHP and regexp references can be found here.
How to use it in your scenario:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
$stmt = sqlsrv_query($conn, $showNoteInfo);
}
if (isset($_POST['noteid']))
{
if (empty($_POST['noteid']))
{
$notes = 'No Data';
}
if (sqlsrv_has_rows($stmt))
{
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
echo "<div class='custom-font title-container'>
<div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
<div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editGeneralNote()'> </div>" . "<div data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>" . " <div class='save-note fa fa-thumbs-up' onclick='saveGeneralNote(); submitNoteText();'></div></div>
</div>";
$note = preg_replace('%(SELECT|FROM|WHERE)%m', '<span style="color: green;">$1</span>', $data['Note']);
echo "<textarea spellcheck='false' readonly id='ta1'>$note</textarea>";
}
else
{
echo "No data found";
}
}
Related
Hi,
i am coding a homepage to learn php and javascript. I decided to use a livesearch using jQuery and php.
It is working well ,but i wonder how i can integrate to the found titles an onclick function that will redirect to the viewpost.php so it opens the clicked title and opens the post.
My HTML search part on index page:
<!-- Search Widget -->
<div class="card my-4">
<div class="card bg-success">
<h5 class="card-header">Search</h5>
<div class="card-body">
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search country..." />
<div class="result"></div>
</div>
</div>
</div>
</div>
jQuery part for livesearch that redirect to php page(backend-search.php)
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
PHP backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
require_once "pdoconfig.php";
// Attempt search query execution
try{
if(isset($_REQUEST["term"])){
// create prepared statement
$sql = "SELECT * FROM articles WHERE title LIKE :term";
$stmt = $db->prepare($sql);
$term = $_REQUEST["term"] . '%';
// bind parameters to statement
$stmt->bindParam(":term", $term);
// execute the prepared statement
$stmt->execute();
if($stmt->rowCount() > 0){
while($row = $stmt->fetch()){
echo "<p>" . $row["title"] . "</p>";
}
} else{
echo "<p>No matches found</p>";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($db);
?>
That is my table structure called articles:
id title content categorie_id pubdate views short_details
And finally my viewpost.php
<?php
$stmt = $db->prepare('SELECT id, title, text, pubdate FROM articles WHERE id = :id');
$stmt->execute(array(':id' => $_GET['id']));
$row = $stmt->fetch();
//if post does not exists redirect user.
if($row['id'] == ''){
header('Location: ./');
exit;
}
echo "<br>";
echo "<div class='card mb-4'>" . "<div class='card-body'>";
echo "<h2 class='card-title'>";
echo $row['title'] . "</h2>";
echo "<div class='card-footer text-muted'>";
echo $row['pubdate'];
echo "</h2>";
echo "<p class='card-text'>";
echo $row['text'];
echo "</p>";
echo '</div>';
?>
Do i need to get the articles id with the jQuery and somehow post it onclick to viewpost.php ?
I do appreciate all help ..
You Need To Change This PHP "backend-search.php" File :
This Code To
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>" . $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
This Code
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch())
{
echo "<p>". $row["title"] . "</p>";
}
}
else
{
echo "<p>No matches found</p>";
}
I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.
i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>
The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter
To generate the stockroom drop down list
function einv_generateStockrmSelectDropdown($Stockrm,$field,$dropdown) {
//connect to database
base_connectDatabase();
echo "<select id=\"stockrm\" name=\"".$field."[]\" multiple=\"multiple\" style=\"align:left\" class=\"form-control\">";
if (isset($Stockrm) && ($Stockrm != "")) {
$stockrmname = einv_getStockrmDetail($Stockrm);
echo "<option value=\"". $Stockrm ."\">". $stockrmname['einv_stockrm_name'] ."</option>";
} else {
$Stockrm = 0;
}
$getStockrmSQL = base_executeSQL("SELECT * FROM einv_stockroom WHERE einv_stockrm_id<>" . $Stockrm . " ORDER BY einv_stockrm_name");
while ($Stockrmdata_row = base_fetch_array($getStockrmSQL)) {
if (base_num_rows($getStockrmSQL)!= 0) {
echo "<option value=\"".$Stockrmdata_row['einv_stockrm_id']."\">".$Stockrmdata_row['einv_stockrm_name']."</option>";
}
}
echo "</select>";
echo "<script src=\"../terms_base/js/jquery.multiple.select.js\"> </script>";
//Input some codes to split the dropdown and make it into the setSelects. By default, the first time = AutoSelectAll
if(isset($dropdown) && ($dropdown != "")) { //dropdown = 1;2;3
$SDDArrays = explode(";", $dropdown);
$countTrap0 = count($SDDArrays);
$drop = "$('#stockrm').multipleSelect(\"setSelects\", [";
$counting = 1;
foreach ($SDDArrays as &$value) {
if ($countTrap0 != $counting) {
$drop .= "'". $value . "',";
} else {
$drop .= "'". $value . "'";
}
$counting++;
}
$drop .= "]);\n";
} elseif (isset($dropdown)) { //dropdown=
$drop = "$('#stockrm').multipleSelect(\"uncheckAll\")";
} else { //
$drop = "$('#stockrm').multipleSelect(\"checkAll\")";
}
echo "<script>\n";
echo "$(function() {\n";
echo "".$drop."";
echo "});\n";
echo "$(\"#stockrm\").multipleSelect({ onClose: function() {
document.getElementById('search').click();
}});\n";
echo "$(\"#stockrm\").multipleSelect();\n";
echo "</script>";
//close the database
base_closeDatabase();
}
//This function is use to add new stock room
//code = stock room code
//name = stock room name
//desc = stock room description
//remark = stock room remark
//cat = stock room category
add stockroom function
function einv_addStockrm($code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
base_executeSQL("INSERT INTO einv_stockroom (einv_stockrm_code, einv_stockrm_name, einv_stockrm_desc, einv_stockrm_remark, einv_stockrm_cat)
VALUES ('" . $code . "', '" . $name . "', '" . $desc . "', '" . $remark . "', '" . $cat . "')");
base_addTransactionLog('Manage Stock Room', 'Add',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/stockrm_list.php";';
echo '</script>';
//close the database
base_closeDatabase();
}
Edit stockroom
function einv_editStockrm($srid,$code,$name,$desc,$remark,$cat)
{
//connect to database
base_connectDatabase();
$User = base_getUserDetail($_SESSION['uID']);
$Stockroom = einv_getStockrmDetail($srid);
base_executeSQL("UPDATE einv_stockroom
SET einv_stockrm_code='" . $code . "',
einv_stockrm_name='" . $name . "',
einv_stockrm_desc='" . $desc . "',
einv_stockrm_remark='" . $remark . "',
einv_stockrm_cat = '" . $cat . "'
WHERE einv_stockrm_id=" . $srid . "");
base_addTransactionLog('Manage Stock Room', 'Edit',
"
Stock Room Code = " . $code . " ||
Stock Room Name = " . $name . " ||
Stock Room Description = " . $desc . " ||
Stock Room Remark = " . $remark . " ||
Stock Room Category = " . $cat . "
");
//go to stock room page
echo '<script type="text/javascript">' . "\n";
echo 'window.location="../einventory/view_stockrm.php?id='. $srid .'";';
echo '</script>';
//close the database
base_closeDatabase();
}
File name: add_Stockroom.php and edit_stockroom.php
I have a dropdown list named Stockroom where it displays an array of values.
Example:
Stockroom
[A]
[B]
[C]
When user clicks on [A], it will display relevant data fields that [A] possess (appears below stockroom ddl).
And as user clicks on [B], there is an onchange function that will then show [B] data fields (fields in A is deleted and replaced with B).
I am able to add the initial values however, as i want to edit and change the stockroom from [A] to [B] which will result in a whole new data to be stored, i am unable to do so.
Any ideas?
I believe i have to amend my edit stockroom function where i require a set of coding such as
If the array is selected, i have to delete existing data and add new data in accordance to the selected ID.
Right now I have a grid and each grid part/bit contains an image, the name of the item and different buttons that can delete the item from the mysql database and update the price. What I want to do know is that when a user say clicks on the image a window would pop up where extra information would be displayed. However it is not a pop up in a usual sense that it would create another window but rather a pop up within the current window/tab. E.g. When you press on a photo in Facebook it creates almost like a popup on which you can comment or change to the next photo. Does anyone have any idea on how to do this or at least what is the whole thing/process called?
Sorry if I can't give a proper name but I don't know it myself :/
Here is the code to what I have now. I would prefer an actual code solution but if you can lead me to where I should look for it I would also be happy. I tried looking online however everything I get is window pop ups.
<div class="boxes">
<?php
$ID = $_SESSION['SESS_MEMBER_ID'];
$con = mysql_connect("", "", "");
if (!$con){
die("Cannot connect: " . mysql_error());
}
mysql_select_db("test", $con);
$sql = "SELECT * FROM items WHERE member_id = $ID";
$myData = mysql_query($sql, $con);
$dir = 'Images';
$symbol = '\\';
$end = 'r.jpg';
$currency = '£';
while($record = mysql_fetch_array($myData)) {
$real_name = str_replace('_', ' ', $record['Name']);
$result = $dir . $symbol . $record['Name'] . $end;
$value = $currency . $record['price_now'];
$link = $record['url'];
echo "<div class = frame>";
echo "<div class = bit-3>";
echo "<div class = box>" . "<img src=" . $result . " alt=some_text>";
echo "<br />";
echo "<br />";
echo $real_name;
echo "<br />";
echo "<br />";
echo "Price now: " . $value;
echo "<form action = member-profile-page.php method = post>";
echo "Desired price: ";
echo "<td>" . "<input type = text name = desired_price value = " . $record['desired_price'] . " </td>";
echo "<td>" . "<input type = hidden name = hidden value = " . $record['Id'] . " </td>";
echo " ";
echo "<td>" . "<input type = submit name = update value = Update" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = delete value = Delete" . " </td>";
echo "<br />";
echo "<br />";
echo "<td>" . "<input type = submit name = buy value = Buy" . " </td>";
echo "</form>";
echo "</div>";
echo "</div>";
echo "</div>";
}
if (isset($_POST['buy'])){
$query = "select url from items where Id = '$_POST[hidden]'";
if ($result = mysql_query($query)) {
$row = mysql_fetch_assoc($result);
$code = $row['url'];
echo "$code";
header("Location: $code");
}
};
if (isset($_POST['update'])){
$UpdateQuery = "UPDATE items SET desired_price = '$_POST[desired_price]' WHERE Id = '$_POST[hidden]'";
mysql_query($UpdateQuery, $con);
};
if (isset($_POST['delete'])){
$DeleteQuery = "DELETE FROM items WHERE Id = '$_POST[hidden]'";
mysql_query($DeleteQuery, $con);
};
mysql_close($con);
?>
</div>
Sounds like you're looking for an overlay:
http://jquerytools.org/demos/overlay/index.html
or a modal:
https://jqueryui.com/dialog/
These are by no means the only examples; there are hundreds of such solutions. These will get you started, though. Good luck!
What you think about is just a layer in the current browser viewport, having some controls to let the user handle it like a "desktop window".
There are quite a lot of JS frameworks offering handy solutions for this, i.e. jQuery UI. Within there, look for "dialog"