I want to search a table by inputing a random number for the ID, and for it to be successful, it has to match the specified tag. So far I have:
$query = "SELECT * FROM web_db WHERE P_Id = " . $random;
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_array($result)){
$name = $row[$id];
echo 'ID:' . $name . '<br>';
$name = $row[$url];
echo 'URL: ' . $name . '<br>';
$name = $row[$tag];
echo 'Tag:' . $name . '<p>';
}
}
This brings up one entry, any tag. How can I have it repeat until Tag matches a specified value?
You don't. SELECT statement returns everything that matches the followed conditions. So, if you want to query for a specific tag entry disregarding the P_Id, do this :
$query = "SELECT * FROM web_db WHERE tag = '".$tag."' ORDER BY RAND() LIMIT 1";
RAND() in this case will order the list randomly, while the query returns the first result that matches the tag used.
$result = mysql_query($query);
if(count($result) > 0) {
while($row = mysql_fetch_array($result)) {
echo 'ID:' . $row['id'] . '<br>';
echo 'URL: ' . $row['url'] . '<br>';
echo 'Tag:' . $row['tag'] . '<p>';
}
} else {
echo 'no entries found';
}
if("sometag" === $name) break;
that exits the while loop. after you exit, you should check again to see if the tag was found or not
Related
I have made a blog in PHP, on Post.php with If isset get I am checking Post ID and than getting slug of same ID from database and accessing the post with that slug.
The issue is its generating Url like: Post.php?Slug=postname-title
I want to make it Post.php?postname-title OR urls.com/postname-title
Please note I am getting post from database matching with slug If any how I do not set php to Get in url it is not getting value from the same slug.
Please guide if it will be done via .htaccess or any other way?
<?php
// add mysql_real_escape_string to slug, to prevent sql injection
$slug = $_GET["slug"];
$sql = "SELECT * FROM posts WHERE slug = '" . mysqli_real_escape_string($db, $_GET["slug"]) . "'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<div id='post-details'>" . "Posted on " . $row["post_date"] . " -- " . "Last Update " . $row["last_edited"] .
"</div>";
if (loggedin()) { echo "<div id='postactions'>This Post:<a href='create_note.php?id=" . $row["id"] . "'>Add Notes</a>";
echo 'Delete Post';
echo 'Edit</div>'; }
$cat_id = $row["cat_id"];
$sql = "SELECT * FROM categories WHERE id = $cat_id";
$resultone = mysqli_query($db, $sql);
if (mysqli_num_rows($resultone) > 0) {
// output data of each row
while ($rowone = mysqli_fetch_assoc($resultone)) {
$cat_name = $rowone["name"];
echo "<div id='post-category'>" . "Category: <a href='all-categories.php?cat_id=$cat_id'>$cat_name</a>" . "</div>";
}
}
echo "<p>" . htmlspecialchars_decode($row["body"]) . "</p>";
$_SESSION["post_id"] = $row["id"];
$postid = $row["id"];
}
} else {
echo "0 results";
}
?>
If you want a simple .htaccess version, you could use the following rule:
RewriteRule ^post/(.+) Post.php?Slug=$1
This will change your URL from a pretty URL like: yourdomain.com/post/postname-title to yourdomain.com/Post.php?Slug=postname-title
I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here
How i separate the first result of for each loop and remaining. I have 2 divs, i want first result to be displayed there and rest on another div.
Also is there any way that i can get json decode without for each loop, i want to display result based on for each values from database, and querying database in for each loop is not recommended.
Here is my code, What i want
<div class="FirstDiv">
Result1
</div>
<div class="RemDiv">
Remaining result from for each loop
</div>
Here is full code
$data = json_decode($response->raw_body, true);
$i = 0;
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
if (++$i == 6)
break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if (mysqli_num_rows($rs)==1) //uid found in the table
{
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
}
Try this:
$data = json_decode($response->raw_body, true);
$i = 0;
echo '<div class="FirstDiv">'; // add this line here
foreach( $data['photos'][0]['tags'][0]['uids'] as $value ) {
if (++$i == 6) break;
$check = "SELECT fullname FROM test_celebrities WHERE shortname = '$value[prediction]'";
$rs = mysqli_query($con,$check);
if ( mysqli_num_rows($rs) == 1 ) { //uid found in the table
$row = mysqli_fetch_assoc($rs);
$fullname= $row['fullname'];
}
// Echo celebrity information:
echo 'Celebrity Name: ' . $fullname . '<br/>';
echo 'Similar: ' . $value['confidence']*100 .'%'. '<br/><br/>';
echo "<img src='actors/$value[prediction].jpg'>";
echo "<hr/>";
if ($i==1) { echo '</div><div class="RemDiv">'; }; // add this line here
}
echo '</div>'; // close the last tag
$predictions=array();
foreach($data['photos'][0]['tags'][0]['uids'] as $value) {
$predictions[]="'" . mysqli_real_escape_string($con, $value[prediction]) . "'";
}
$check="SELECT fullname FROM test_celebrities WHERE shortname IN (" . implode(',' $predictions) . ")";
$rs = mysqli_query($con,$check);
while ($row = mysqli_fetch_assoc($rs)) {
if (!$count++) {
// this is the first row
}
But note that you now have two sets of data which are sorted differently - hence you'll need to iterate through one and lookup values in the other.
I am trying to figure out how to mark a dropdown option as selected by checking it's value, but the value is coming from another query.
I get the $FK_TopicID from the query called $quickedit. The dropdown list is generated by a different query called $topresult. I have an IF/ELSE statement that is supposed to print SELECTED inside of the option like <option value="the Topic ID" SELECTED> when the $FK_TopicID is equal to $row['TopicID'].
I am just not sure how to check the $FK_TopicID within the while loop for $topresult. Any ideas?
<?php
$NewsID = $_GET["n"];
$quickedit = mysql_query("SELECT * FROM News LEFT JOIN Topics on Topics.TopicID = News.FK_TopicID WHERE NewsID = $NewsID ORDER BY TopicName ASC, NewsTitle");
$row = mysql_fetch_array($quickedit);
echo "<p>" . $FK_TopicID . "</p>";
/* additional php... */
$topresult = mysql_query("SELECT * FROM Topics WHERE FK_UserID=$_SESSION[user_id] ORDER BY TopicSort, TopicName");
while($row = mysql_fetch_array($topresult)) {
if ( $row['TopicID'] == $FK_TopicID){ /* $FK_TopicID not printing value here */
$selected = " SELECTED";
} else {
$selected = "";
}
echo '<option value=\"' . $row['TopicID'] . '" ' . $selected . '>' . $row['TopicName'] . '</option>';
}
?>
I have no clue about the structures of the database, but I'll give it a shot
Does this output something you want?
<?php
$NewsID = $_GET['n'];
$quickedit = mysql_query("SELECT * FROM News LEFT JOIN Topics on Topics.TopicID = News.FK_TopicID WHERE NewsID = $NewsID ORDER BY TopicName ASC, NewsTitle");
$topresult = mysql_query("SELECT * FROM Topics WHERE FK_UserID=$_SESSION[user_id] ORDER BY TopicSort, TopicName");
echo "<p>" . $FK_TopicID . "</p>";
while($row = mysql_fetch_array($quickedit)) {
while($row2 = mysql_fetch_array($topresult)) {
if ( $row2['TopicID'] == $row['FK_TopicID']){
$selected = " SELECTED";
} else {
$selected = "";
}
echo '<option value=\"' . $row2['TopicID'] . '" ' . $selected . '>' . $row['TopicName'] . '</option>';
}
}
?>
This code loops through both queries and if the TopicID from $topresult is equal to the FK_TopicID from $quickedit, it will be selected.
Below is a function in PHP I created which returns some product information in an array. On the web page where I am calling this function I want to be able to specify exact array elements for example just the product description ($result2['itm_desc']). Please can someone point me in the right direction as to do this. I would assume you call a function like fetch array but i'm not quite sure how to execute this.
public function getAllReelImages(){
$sql = "SELECT id FROM $this->table3 WHERE itm_cat = 2 ORDER BY id ASC";
echo "<br /><br />";
$stmt = mysqli_query($this->connection, $sql);
/*fetch values*/
while($result = mysqli_fetch_array($stmt)){
echo "<br /><br />";
$sql2 = "SELECT itm_details.id,itm_details.itm_make,itm_details.itm_model,itm_details.itm_desc,itm_pic_detail.itm_pic_name, itm_value.itm_sale_price
FROM
itm_details, itm_pic_detail, itm_value
WHERE
itm_details.id = {$result['id']} AND itm_pic_detail.id = {$result['id']}
AND itm_value.id = {$result['id']} ORDER BY id ASC";
$stmt2 = mysqli_query($this->connection, $sql2);
while($result2 = $stmt2->fetch_array()){
echo ($result2['id']); echo"<br />";
echo ($result2['itm_make']); echo"<br />";
echo ($result2['itm_model']); echo"<br />";
echo ($result2['itm_desc']); echo"<br />";
echo ($result2['itm_sale_price']); echo"<br />";
echo "<img src='$this->dir"."{$result2['itm_pic_name']}'><br />";
echo"<br />";
echo $value;
}
}
}
First of all.. Your code is pretty bad. I made it little bit more clear. For example: echo ($result2['id']); echo"<br />"; TO-> echo $result2['id'] . '<br />'; (for future references.)
They way your code is at the moment. You wont add anything to an array, since you echo them right away. I made my version, that would first create the array and then later you can use that array..in any way you want :)
And doesn't the ORDER BY use by default as ASC?
I also changed the first query more dynamic.
NOTE: I'm not very good with mysql table joining, somebody must validate the second query. But in my eyes, its absolutely incorrect. However, I'm posting this in the reference for creating an array with a function and then displaying it.
NOTE2: I hope your question was about PHP o.0
# This should be in some class ?!
function getAllReelImages ($category) {
$sql = "SELECT * FROM `" . $this->table3 . "` WHERE `itm_cat` = '" . $category . "' ORDER BY `id` ASC";
$stmt = mysqli_query($this->connection, $sql);
while($result = mysqli_fetch_array($stmt)) {
$sql2 = "SELECT `itm_details.id`, `itm_details.itm_make`, `itm_details.itm_model`, `itm_details.itm_desc`, `itm_pic_detail.itm_pic_name`, `itm_value.itm_sale_price` FROM `itm_details`, `itm_pic_detail`, `itm_value` WHERE `itm_details.id` = '" . $result['id'] . "' AND `itm_pic_detail.id` = '" . $result['id'] . "' AND `itm_value.id` = '" . $result['id'] . "' ORDER BY `id` ASC";
$stmt2 = mysqli_query($this->connection, $sql2);
while($result2 = $stmt2->fetch_array()){
$returns[$result2['id']]['id'] = $result2['id'];
$returns[$result2['id']]['itm_make'] = $result2['itm_make'];
$returns[$result2['id']]['itm_model'] = $result2['itm_model'];
$returns[$result2['id']]['itm_desc'] = $result2['itm_desc'];
$returns[$result2['id']]['itm_sale_price'] = $result2['itm_sale_price'];
$returns[$result2['id']]['itm_pic_name'] = $this->dir . $result2['itm_pic_name'];
}
}
return $returns;
}
# Display the results:
echo '<br /><br />';
foreach (getAllReelImages(2) as $img_id => $img_value) {
echo $img_id . '<br>';
echo $img_value['itm_make'] . '<br>';
echo $img_value['itm_model'] . '<br>';
echo $img_value['itm_desc'] . '<br>';
echo $img_value['itm_sale_price'] . '<br>';
echo $img_value['itm_pic_name'] . '<br>';
echo '<hr>';
}
echo '<br />';