I'm using this 2 plugins
http://www.wpexplorer.com/wordpress-user-contact-fields/
and
WooCommerce
The 1st parameter, in this case the number "1" refers to the id of the user, how con I change it to be dynamic? So, depending on the user I get its own specific information
<h2>Personal</h2>
<?php
echo '<ul>';
echo '<li>Direccion: ' .get_user_meta(1,'address',true) . '</li>';
echo '<li>Compañia: ' .get_user_meta(1,'company',true) . '</li>';
echo '<li>Birth dAte: ' .get_user_meta(1,'birth',true) . '</li>';
echo '<li>Gender: ' .get_user_meta(1,'gender',true) . '</li>';
echo '<li>phone: ' .get_user_meta(1,'phone',true) . '</li>';
echo '</ul>';
?>
thanks
Don't try to make a function do something it wasn't intended to do. Write your own. Especially for something this simple.
function getUserStuff($id, $item){
$item = mysql_real_escape_string($item);
$id = mysql_real_escape_string($id);
$q = mysql_query("SELECT `".$item."` FROM `users` WHERE `id` = '".$id."'");
$z = mysql_fetch_assoc($q);
return (mysql_num_rows($q) > 0) ? $z[$item] : false;
}
This is just an example. I used a deprecated function for simplicity but you should use a different API.
Related
I'm not new here but I also do not ask questions because whenever I have a problem I find a solution in questions related here in the forum or in blogs, but I did not have any success with this problem.
In a database I have the tables posts and categories that are related, and in a single MySQL query I am displaying the title of the posts within their categories. So far so good, everything working. However within the while loop structure the tag with the is-sub class can not be repeated. Is there any way to stop the repetition of this while and then repeat it again?
I thank you for your help
echo '
<nav class="navbar">
<ul>';
$sql = Query("SELECT * FROM posts INNER JOIN categories ON post_category = category_id ORDER BY post_category, post_title");
$is_category = NULL;
while ($row = mysqli_fetch_assoc($sql)) :
if ($row['post_category'] != $is_category) {
echo '<li class="has-sub">' . $row['category_title'] . '';
$is_category = $row['post_category'];
}
// stop loop
echo '<ul class="is-sub">';
// return loop
echo '<li>' . $row['post_title'] . '</li>';
// stop loop
echo '</ul>';
// return loop
echo '</li>';
endwhile;
echo '
</ul>
</nav>';
If I understood what you are trying to do, I think the code below would work. If the is_sub tag is really meant to show only once then this could work:
<?php
echo '
<nav class="navbar">
<ul>';
$sql = Query("SELECT * FROM posts INNER JOIN categories ON post_category = category_id ORDER BY post_category, post_title");
$is_category = NULL;
$issub = false;
while ($row = mysqli_fetch_assoc($sql)) :
if ($row['post_category'] != $is_category) {
echo '<li class="has-sub">' . $row['category_title'] . '';
$is_category = $row['post_category'];
echo '<ul class="is-sub">';
}
if(!$issub) {
echo '<ul class="is-sub">';
$issub = true;
}
echo '<li>' . $row['post_title'] . '</li>';
echo '</ul>';
echo '</li>';
endwhile;
echo '
</ul>
</nav>';
?>
I have this function:
function get_content($text_to_match) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
But when I call it like:
<div>
<?php
for ($i = 1; $i < count(get_content("text_to_match")); $i++) {
echo '<article>' .
'<h3>' . get_content("text_to_match")["string1"] . '</h3>'.
'<p>' . get_content("text_to_match")["string2"] . '</p>' .
'</article>';
}
?>
</div>
I only get the first match in the DB repeated as many times as the number of found items.
Where have I gone wrong?
use this code then fetch data properly
while($content = mysql_fetch_array($cont))
{
return $content;
}
Your logic is at fault. You are calling get_content function to get all matches for the loop, as well as to get individual elements out of the list. This is:
bad logic - the 2nd use case doesn't make sense
excessive - you shouldn't need to run a database query just to output an already retrieved result
What you probably want to do is:
foreach (get_content('text_to_match') as $content) {
echo '<article>';
echo '<h3>' . $content['string1'] . '</h3>';
echo '<p>' . $content['string2'] . '</p>';
echo '</article>';
}
With a few modifications in combination with tips from #Anant and #Unix One's answer, I arrived at this working solution:
Function definition
function get_content($text_to_match, $multiple=false) {
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE one_column_name LIKE '%{$text_to_match}%' OR another_column_name LIKE '%{$text_to_match}%'";
$cont = mysqli_query($connection, $query);
if ($multiple) {
$content_array = [];
while($content = mysqli_fetch_array($cont)) {
$content_array[] = $content;
}
return $content_array;
} else {
if($content = mysqli_fetch_assoc($cont)) {
return $content;
} else {
return null;
}
}
}
Function calls
<?php
/* multiple items */
foreach(get_content("text_to_match", true) as $content) {
echo '<article>' .
'<h3>' . $content["string1"] . '</h3>' .
'<p>' . $content["string2"] . '</p>' .
'</article>';
}
?>
<?php
/* one item */
echo get_content("text_to_match")["string"];
?>
I'm looking to create a function to display prev-next buttons on the header of a one page site.
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT 1";
The content for the entire site comes off a primary key in the database titled "issue_no" everything inside issue_no is the content to be displayed on the one page.
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}
}
This is displayed on index.php
Currently, it displays the latest issue pending on the publish date, but I would like to add the function to go back to previous and next editions.
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Also - how would I go about making sure these each have clean URLs?
e.g. http://www.example.com/issue/023
Any help much appreciated.
I've tried reading up on pagination, but I'm finding it a little complicated to wrap my head around this one.
Thanks.
You say:
On top of this, I'd like to rollout all issues inside a dropdown select menu that allows you to select say "Issue 23" and it would link you through to the appropriate content contained in that issue.
Assuming (for example) an URL like “http://www.example.com/issue.php?issue=23” (for now postponed the ‘clean’ URL question) you can resolve all questions in this way:
$issueId = $_GET['issue'];
/* 01: Retrieve ALL id */
$result = $con->query( "SELECT GROUP_CONCAT( `issue_no` ORDER BY `issue_no` DESC ) FROM `issue`" );
$allId = explode( ',', $result->fetch( PDO::FETCH_NUM )[0] );
/* 02: Check if $issueId exists and set previous/next id */
$prev = $next = False;
$found = array_search( $key, $allId );
if( $found === False ) $found = count( $allId )-1;
if( $found > 0 ) $prev = $allId[$found-1];
if( $found < count($allId)-1 ) $next = $allId[$found+1];
/* 03: Retrieve current issue: */
$result = $con->query( "SELECT * FROM `issue` WHERE `issue_no` = '{$allId[$found]}'" );
$row = $result->fetch_assoc();
/* 04: Output previous/next page link: */
if( $prev !== False ) echo "Prev Page";
else echo "<span class=\"inactive\">Prev Page</span>";
if( $next !== False ) echo "Next Page";
else echo "<span class=\"inactive\">Next Page</span>";
// Your code from here
Code above is only as example. By this way, all issue_no are stored in $allId variable, so you can easy implement also the dropdown menu. The issue_no fields are retrieved in descending order, if you prefer ascending you can change first query (#01) in ORDER BY issue_no ASC.
Note that if the user don't ask for any specific issue (i.e. calling http://www.example.com/issue.php), the current issue is set to first array value of $allId (#02): if you prefer to produce an alert like “This issue doesn't exists” you have to modify the script in this way:
$found = array_search( $key, $allId );
if( $found === False )
{
// Your error routine here
}
else
{
if( $found > 0 ) $prev = $allId[$found-1];
(...)
}
In the output of previous/next page URLs (#04), I use a basic <a href> tag, but you can use buttons.
Clean URLs
I strongly recommend to produce first a full working code ignoring the ‘clean’ URL question. Then, all you will need to change will be only one row.
By the way, to activate clean urls, you have to modify the .htaccess file of your site in a way like this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^issue/.*$ /issue.php [NC,L]
</IfModule>
then, in your issue.php script, you have to change $issueId = $_GET['issue']; with:
$issueId = array_pop( explode( '/', $_SERVER['REQUEST_URI'] ) );
This RewriteRule is only an example, actually I think you are interested in clean URLs for all your site, so the best solution can be to redirect all incoming URLs to a redirect.php that process the REQUEST_URI and include appropriate page or echoes ‘Not Found’ message.
Here you can find more about basics on RewriteRule
These code I haven't tested, not stable at all. You have to optimize it.
Function to get data
In PHP:
<?php
$issueno = $_GET["issueno"];
if($issueno == null){
$issueno = 0;
}
$servername = "localhost";
$username = "username";
$password = "password";
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM `issue` ORDER BY `issue_no` DESC LIMIT " + $issueno + ",1";
if($row = mysqli->query($query, MYSQLI_USE_RESULT))
{
/* row is the row selected */
echo "<article id='date_published'><p>Date published: " . $row['date_published'] . "</p></article>";
echo "<article id='article_head'>" . $row['article_head'] . "</article>";
echo "<article id='article_body'>" . $row['article_body'] . "</article>";
echo "<article id='vidpicks_embed'>" . $row['vidpick'] . "</article>";
echo "<article id='quote_body'>" . $row['quote_body'] . "—</article>";
echo "<article id='quote_auth'>" . $row['quote_auth'] . "</article>";
echo "<article id='wotd_body'>" . $row['wotd_body'] . "</article>";
echo "<article id='wotd_desc'>" . $row['wotd_desc'] . "</article>";
}else{
echo "It does not exist";
}
$mysqli->close();
?>
NEXT
In Javascript, by redirecting with a issueno parameter
function next(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
//Added 1 here as NEXT
currentissueno = 0;
}
//Maximum issues No. OutOfBounds not handled... I have to sleep now
currentissueno++;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
PREVIOUS
In Javascript, by redirecting with a issueno parameter
function prev(){
var currentissueno = getQueryVariable("issueno");
if (currentissueno == null){
alert("The last previous page");
return;
}
currentissueno--;
//Redirect (should use window.location.href instead of static url)
//window.location = window.location.href + "?issueno=" + currentissueno;
window.location = "http://www.example.com/index.php?issueno=" + currentissueno;
}
Function to GET url parameter
Required. From Using the GET parameter of a URL in JavaScript
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return null;
}
I'm running a script that fetches a row from a MySQL table and is supposed to then pass certain variables from that row to the next page to be used in a form that allows user updating.
Here's the excerpt from the script that is trying to pass the variables to the next page:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
If I omit everything after "&game_id=" in the href, it displays fine. However, once I start adding the variables, it cuts off the function and stops displaying the page.
Am I doing something simple wrong with the syntax? I've tried playing around with different ways to write it, but to no avail. Do I need to utilize a http_build_query() to make this work?
Here's the entire script code if you need more info:
<?php
// Connect to the database:
require ('../mysqli_connect.php');
// Make the query for games from the schedule database and determine the game location:
$q = "SELECT tl.game_date, tl.game_time, tl.away_team, tl.home_team, tl.home_score,tl.away_score, tl.arbiter_id, us.football_location, us.football_map
FROM test_league tl
INNER JOIN user_schools us ON (tl.home_team = us.school_name)
ORDER BY tl.game_id";
$r = mysqli_query($db, $q);
// Declare two variables to help determine the background color of each row:
$i = 0;
$bgcolor = array('row1', 'row2');
// Begin function to print each game as a row:
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '<tr class="' . $bgcolor[$i++ % 2] .'"><td>' . $row['game_date'] . '</td><td>' . $row['game_time'] . '</td><td class="alignleft">' . $row['away_team'] . ' vs<br>' . $row['home_team'] . '</td>';
// Determine if the score has been reported:
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
} else {
echo '<td>' . $row['home_score'] . '<br>' . $row['away_score'] . '</td>';
}
echo '<td>' . $row['football_location'] . '</td><td>' . $row['arbiter_id'] . '</td></tr>';
}
mysqli_free_result ($r);
mysqli_close($db);
?>
Any and all advice is greatly appreciated!
Try this, you've got your speech marks and dots mixed up :)
if ($row['home_score'] == '0' && $row['away_score'] == '0') {
echo '<td><img src="images/report_icon.png" alt="Report Score" /></td>';
}
Hope this helps!
$url = 'www.example.com?' . http_build_query($row,'','&');
I am using the following code:
$result = mysql_query("SELECT * FROM table LEFT JOIN table2
ON table.field = table2.field WHERE ( table.field = '$pid' )
AND ( table.field5 LIKE '%$q%' OR table.field3 LIKE '%$q%'
OR table2.field2 LIKE '%$q%' )");
if (empty($what)) {
$countpls = "0";
} else {
$countpls = mysql_num_rows($result);
}
<?php
if ($countpls > 10) {
echo '<a id=pgnvg href="' . $_SERVER['PHP_SELF'] . '?pg=' . ($startrow + 20) . '&q=' . ($what) . '">Next</a>';
} else {
echo "";
}
$prev = $startrow - 20;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0) {
echo '<a id=pgnvg2 href="' . $_SERVER['PHP_SELF'] . '?pg=' . $prev . '&q=' . ($what) . '">Previous</a>';
} else {
echo "";
}
?>
I want the next to show only if there are more entries to show and previous only if there are more entries to circle back to. It works on the first page bt then on the last page Next shows despite teh fact that there are no more results to show.
I tried adding the 'else' but its still not working.
Any ideas?
if($countpls > 0){
$pg = $_POST['pg']?$_POST['pg']:1;
//if it's not the first page...
if($pg>1){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg-1).'&q='.$what.'">Previous</a>';
}
//if you have more registers to show...
if(($countpls-(($pg-1)*10))>10){
echo '<a id="pgnvg" href="'.$_SERVER['PHP_SELF'].'?pg='.($pg+1).'&q='.$what.'">Next</a>';
}
}
In order to calculate your offset to use in queries, use this:
$offset = ($_POST['pg']-1)*10;
It would help if you would provide the code that's setting $countpls. That might be the part that's causing the problem. Also, the else's are unnecessary. However, try this:
if($countpls - $startrow > 20)
{
echo '<a id=pgnvg href="'.$_SERVER['PHP_SELF'].'?pg='.($startrow+20).'&q='.($what).'">Next</a>';
}
I think it would do you good if you followed a tutorial to grasp the basic concepts. It even comes with the example that could either 1.) replace your current pagination or 2.) fix it.
http://www.phpfreaks.com/tutorial/basic-pagination