MySQL live Query - php

I wonder if someone can help i am trying to incorporate a live search into my website, I have found a tutorial and the appearance side of things is now working, could someone please tell me how i can edit the follow PHP to pull information from only one table.
Table - movies
Fields to echo for each result - Movie, description, Image
At the moment it is pulling information from 2 tables successfully one displays the content of the search the other provides information for category dividers, What i need is to remove the category aspect and pull information from the a single table.
Apologies my PHP knowledge is very limited, hope this best describes the problem.
<p id="searchresults">
<?php
// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT * FROM search s INNER JOIN categories c ON s.cat_id = c.cid WHERE name LIKE '%" . $queryString . "%' ORDER BY cat_id LIMIT 8");
if($query) {
// While there are results loop through them - fetching an Object.
// Store the category id
$catid = 0;
while ($result = $query ->fetch_object()) {
if($result->cat_id != $catid) { // check if the category changed
echo '<span class="category">'.$result->cat_name.'</span>';
$catid = $result->cat_id;
}
echo '<a href="'.$result->url.'">';
echo '<img src="search_images/'.$result->img.'" alt="" />';
$name = $result->name;
if(strlen($name) > 35) {
$name = substr($name, 0, 35) . "...";
}
echo '<span class="searchheading">'.$name.'</span>';
$description = $result->desc;
if(strlen($description) > 80) {
$description = substr($description, 0, 80) . "...";
}
echo '<span>'.$description.'</span></a>';
}
echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
</p>

Replace
SELECT * FROM search s INNER JOIN categories c ON s.cat_id = c.cid WHERE name LIKE '%" . $queryString . "%' ORDER BY cat_id LIMIT 8
with
SELECT * FROM movies WHERE movie LIKE '%" . $queryString . "%' ORDER BY movie LIMIT 8
would be a good start.
Can you carry on from there?
Aside - you wrote 'Movie' for the field name in your description above - I've used a lower case 'M' so you may need to change it.
[edit] In reply to comment #1:
Let's start off simple - replace if ($query) { ... } with
if ($query) {
while ($result = $query ->fetch_object()) { // this line loops through all the results
echo '<img src="search_images/'.$result->image.' />'; // check capital I on 'image'
echo '<strong>'.$result->movie.'</strong>';
echo $result->description.'<br />';
}
}
Basically, you just put $result->myFieldName inside of the while loop to get the data out you want.
Hopefully that should be enough get you going =]

I guess:
<p id="searchresults">
<?php
// PHP5 Implementation - uses MySQLi.
// mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
$db = new mysqli('localhost', 'yourUsername', 'yourPassword', 'yourDatabase');
if(!$db) {
// Show error if we cannot connect.
echo 'ERROR: Could not connect to the database.';
} else {
// Is there a posted query string?
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
// Is the string length greater than 0?
if(strlen($queryString) >0) {
$query = $db->query("SELECT * FROM movies WHERE Movie LIKE '%" . $queryString . "%' ORDER BY Movie LIMIT 8");
if($query) {
// While there are results loop through them - fetching an Object.
while ($result = $query ->fetch_object()) {
echo '<a href="'.$result->url.'">';
echo '<img src="search_images/'.$result->img.'" alt="" />';
$name = $result->movie;
if(strlen($name) > 35) {
$name = substr($name, 0, 35) . "...";
}
echo '<span class="searchheading">'.$name.'</span>';
$description = $result->description;
if(strlen($description) > 80) {
$description = substr($description, 0, 80) . "...";
}
echo '<span>'.$description.'</span></a>';
}
echo '<span class="seperator">Nothing interesting here? Try the sitemap.</span><br class="break" />';
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
// Dont do anything.
} // There is a queryString.
} else {
echo 'There should be no direct access to this script!';
}
}
?>
</p>

Related

How to Check If 10 Most Recent Entries in MySQL DB Begin with a String Using PHP?

I want to allow people to write something like BOLD: or ITALIC: at the beginning of their message to make bold or italic. The only way I can think of is to get the total amount of entries by ID and minus 10 then make an IF statement and minus 9 and so on. Is there a single statement I could query to check if the string in the database begins a certain way and display it in HTML in bold or italic if it does?
<?PHP
$A = "localhost"; // Server Name
$B = "root"; // MySQL Username
$C = ""; // MySQL Password
$D = "sql"; // Database
$CONNECT = new mysqli($A, $B, $C, $D);
if ($CONNECT->connect_error) {
die('<DIV>Connection Failed</DIV>');
}
echo "<DIV>Connected</DIV>";
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
echo "<DIV>Error Sending Message</DIV>";
}
}
$SELECT = 'SELECT * FROM Messages ORDER BY ID DESC LIMIT 10';
$RESULT = $CONNECT->query($SELECT);
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $ROW['Message'] . '</DIV>';
}
}
I added in some code if somebody begins their message with "'", but the type of strpos if statement doesn't work in the while loop for retrieving messages.
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
if (substr($MSG,0,1 == '\'')) {
echo "<DIV>Error Sending Message</DIV>";
} else {
echo "<DIV>Nice Try :')</DIV>";
}
}
In order for this question to have an answer i will sum up what i did in the comments:
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
$message = $ROW['message'];
if(strpos($ROW['message'], 'BOLD:') !== false){
$message = '<strong>'.substr($ROW['message'], 5).'</strong>';
} else if(strpos($ROW['message'], 'ITALIC:') !== false){
$message = '<i>'.substr($ROW['message'], 7).'</i>';
}
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $message . '</DIV>';
}
}
edit: oops i forgot to add the different style tags..
for bold you can wrap the $message in a strong -tag. for italic its the i -tag
edit2: included tags in the code

echoing the error null when there is no matched data in database

I created a simple form that searches the match of the entered username to one in database and displays its first name and last name. I'm having a problem in displaying error. It is supposed to be displaying null or nothing when the username entered doesn't match with the username in the database. I tried echoing null in the else statement, but it still displays the error message.
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=sample;charset=utf8', 'root', '');
if(isset($_POST['search'])) {
$search = $_POST['search'];
$query = $db->prepare("SELECT * FROM search WHERE username=:username");
$query->execute(['username' => $search]);
$row = $query->fetch(PDO::FETCH_OBJ);
if(count($row)) {
echo $row->firstname . ' ' . $row->lastname;
} else {
echo null;
}
}
This is not supposed to be showing:
You should do something like
if(count($row) > 0) {
echo $row->firstname . ' ' . $row->lastname;
} else {
echo null;
}

How to remove 5 characters from the end of every column in a table MySQLi

I'm trying to loop through every row in a table, and remove 5 characters from the end of one column. I have written the following code but it seems to remove 2 characters for some reason.
<?php
$connection = new mysqli('localhost', 'nawd_test', 'password', 'nawd_test');
if ($connection->connect_errno > 0) {
die ('Unable to connect to database [' . $connection->connect_error . ']');
}
$sql = "SELECT *
FROM test";
if (!$result = $connection->query($sql)) {
die ('There was an error running query[' . $connection->error . ']');
}
//Create an array to hold the values of id's already changed
$ids = [];
$newVals = [];
echo '<p>Fetching rows...</p>';
while ($row = $result->fetch_assoc()) {
//Check / Add the id
if (in_array($row['id'], $ids)) {
echo '<p style="red"><strong>Error: Script has repeated itself!</strong></p>';
break;
}
$ids[] = $row['id'];
$rowName = $row['name'];
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
$newVals[] = $newName;
}
//Now loop and update
$newValID = 0;
foreach ($ids as &$id) {
echo '<p>Updating row with ID ' . $id . '</p>';
mysqli_query($connection, "UPDATE test SET name ='" . $newVals[$newValID] . "' WHERE id=" . $id);
echo '<p>Column successfully changed "<em>' . $newVals[$newValID] . '</em>"</p>';
$newValID++;
}
echo '<p style="color: green;"><strong>Script complete!</strong></p>';
?>
Dont do this in php, you can do it with a single sql query:
UPDATE test SET name = LEFT(name, LENGTH(name) - 5)
Change
$newName = substr($rowName, -1);
$newName = rtrim($rowName,$newName);
into
$newName = substr($rowName, 0, strlen($rowName) - 5);
With the way you're working, you could never predict how many characters that would have removed at the end.
Minimum 1, maximum the whole word.
Please read the documentation about rtrim and substr.
try this if you wanna doit inside the query:
update table1 set name=substr(name,-5,length(name))

PHP and mysqli to modify CSS

I was experimenting if I could use a mySQL database to store CSS settings. I set up a simple database "colors" with one table "color" that had simple structure tag and color columns. In that, one row is h1 => red.
<?php
//function to dynamically change CSS
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
?>
When I tried to convert to a function, the code does not work at all.
<?php
//function to dynamically change CSS
function getCSS($tag)
{
$tag = 'h1';
$q = "SELECT * FROM `colors` WHERE `tag`='" . $tag . "'" ;
echo $q . "<br>";
$query = mysqli_query($link, $q);
if ($row = mysqli_fetch_assoc($query))
{
echo $row['color'];
} else
{
echo "error - no such tag";
}
}
getCSS('h1');
?>
Help please?
My guess is that in
$query = mysqli_query($link, $q);
$link goes out of scope and is empty. You should pass it to the function as well.
For the record: using $tag without escaping could be an sql injection attack possibility.
in function, there is no $link, you shoud define it as a global variable.
At the start of your function add a reference to your global DB link:
function getCSS($tag) {
global $link;
...
This should work:
<?php
$link = mysqli_connect('server_host', 'user', 'password', 'database') OR die('Could not connect because: '.mysqli_connect_error());
//function to dynamically change CSS
function getCSS($link, $tag){
$q = 'SELECT * FROM colors WHERE tag = "' . $tag . '"' ;
$r = mysqli_query($link, $q);
if(mysqli_num_rows($r)>0){ // check if there are results
while($row = mysqli_fetch_assoc($r)){
//echo '<pre>';
//print_r($row); // print the result array for debugging
//echo '</pre>';
echo $row['color'] . '<br />';
}
return $row;
} else { // if no result is found
echo 'No such tag';
}
}
// test it:
echo '<br />if tag is h1<br />';
getCSS($link, 'h1');
echo '<br />if tag is h2<br />';
getCSS($link, 'h2');
?>

How can I get the ID and title of a post in PHP?

How can I get the ID and title of a post in PHP? Each post has an ID and a title, and I need to be able to get both.
ID# Title
1013 Name
1025 Name
Your question is a bit unclear. Assuming you use MySQL, you can get the id and the title of a post like this:
<?php
$query = "SELECT id, title FROM table";
$result = mysql_query($query);
if(!$result)
{
echo 'The query failed.<br />';
echo mysql_error();
}
else
{
//check if there are results
if(mysql_num_rows($result) == 0)
{
echo 'No results.';
}
else
{
//loop through the results
while($row = mysql_fetch_assoc($result))
{
echo 'ID: ' . $row['id'] . ', name: ' . $row['title'];
}
}
}

Categories