Shortcode WordPress with Query SQL - php

I wanted to create a shortcode so I can "connect" my Coppermine gallery with my Wordpress, sadly I haven't been able to do it
I use this in my posts
[cpg album="533"]
To call this function
function cpg_shortcode( $attr ) {
shortcode_atts(
array(
'album' => 1,
), $attr
);
return $album_id = $attr['album'];
return '<script src="http://linklink.net/cpg/api-posts.php"></script>';
}
add_shortcode( 'cpg', 'cpg_shortcode' );
And this is the script file, which has no errors, it work perfectly fine, but I have to get the album id in it
$query = mysql_query("SELECT * FROM `cpgq7_pictures` WHERE aid=$album_id ORDER BY ctime DESC LIMIT 0 , 3");
echo 'document.write(\'';
if(mysql_num_rows($query) == 0){
echo 'No hay fotos';
} else {
echo '<h6>';
while($row = mysql_fetch_array($query)){
$domain = "http://linklink.net/cpg";
$album_url = "$domain/thumbnails.php?album=$album_id#content";
$album_img = "$domain/albums/".$row['filepath'].'thumb_'.$row['filename'];
echo '<img src="'.$album_img.'" alt="" />';
}
echo '<img src="https://i.imgur.com/4wmomUt.png" alt="" /></h6>';
}
echo '\');';
When I try to get the album id from the shortcode it doesn't work
Any help is appreciated.

I copy/pasted your shortcode and this line works as intended:
return $album_id = $attr['album'];
Returns the passed album parameter. If you want, you can use extract to have the id directly as $album available:
extract(shortcode_atts(
array(
'album' => 1,
)
, $attr));
now this looks pretty much wrong:
<script src="http://linklink.net/cpg/api-posts.php"></script>
is for javascript, it has nothing to do with php. just include the sql statement and output directly in your shortcode. changed the way of returning the data (ob_start/get_clean). also, like Dharman mentioned, check out how to execute sql statements safely.
function cpg_shortcode($attr) {
extract(shortcode_atts(
array(
'album' => 1,
)
, $attr));
ob_start();
$query = mysql_query("SELECT * FROM `cpgq7_pictures` WHERE aid=$album ORDER BY ctime DESC LIMIT 0 , 3");
if (mysql_num_rows($query) == 0) {
echo 'No hay fotos';
} else {
echo '<h6>';
while ($row = mysql_fetch_array($query)) {
$domain = "http://linklink.net/cpg";
$album_url = "$domain/thumbnails.php?album=$album#content";
$album_img = "$domain/albums/" . $row['filepath'] . 'thumb_' . $row['filename'];
echo '<img src="' . $album_img . '" alt="" />';
}
echo '<img src="https://i.imgur.com/4wmomUt.png" alt="" /></h6>';
}
return ob_get_clean();
}
add_shortcode('cpg', 'cpg_shortcode');

Related

Warning: urlencode() expects parameter 1 to be string, array given in ... on line

I am a beginner programmer. Only in php.
On php, am at procedural style. Not on oop or pdo yet. Hence, you see mysqli and procedural style.
I am building a SERP with pagination. Like google, when they show you your keywords search result.
Don't mistake my thread. Not trying to prevent Sql injection as I managed to do it using prepared statements.
Learning to use urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags to breakup the html of my SERPs.
On this occasion, I am having problem using urlencode() properly.
I get this error:
Warning: urlencode() expects parameter 1 to be string, array given in ... on line ...
Following are the concerned lines as I urlencode() their values so no user (keywords searcher) can inject html tags to breakup the html of my SERP:
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
The above vars contain one values each as each $_GET contains one value each, even though $_GET is a a global variable (array). So here, nothing to do with arrays or more than one value per each variable.
Issue is on this following line that comes just after the WHILE loop:
LINE 145
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
Here is the code context:
//ERROR REPORTING FOR DEVMODE ONLY.
ini_set('display_errors','1');
ini_set('display_startup_errors','1');
error_reporting(E_ALL);
//MYSQLI CONNECTION.
mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$server = 'localhost';
$user = 'root';
$password = '';
$database = 'brute';
if(!$conn = mysqli_connect("$server","$user","$password","$database"))
{
echo 'Mysqli Connection Error' .mysqli_connect_error($conn);
echo 'Mysqli Connection Error Number' .mysqli_connect_errno($conn);
}
if(!mysqli_character_set_name($conn) == 'utf8mb4')
{
echo 'Initial Character Set: ' .mysqli_character_set_name($conn);
mysqli_set_charset("$conn",'utf8mb4');
echo 'Current Character Set: ' .mysqli_character_set_name($conn);
}
//PAGINATION SECTION.
$search = $_GET['search']; //Keyword(s) to search.
$col = $_GET['col']; //MySql Tbl Col to search.
$tbl = $_GET['tbl']; //MySql Tbl to search.
$max = $_GET['max']; //Max Result per page.
$page = $_GET['page']; //Serp Number.
//QUERY DATABASE FOR KEYWORD COUNT.
$query = "SELECT COUNT(id) From links WHERE keyword = ?";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt,$row_count);
if(mysqli_stmt_fetch($stmt))
{
echo 'Row Count: ' .$row_count; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($conn);
echo 'Error: ' .mysqli_stmt_errno($conn);
}
mysqli_stmt_close($stmt);
}
else
{
echo 'Search Preparation Failed!';
}
//mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//START KEYWORD SEARCH & OUTPUT RESULT
echo $offset = ($page*$max)-$max; echo '<br>';
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
$query = "SELECT id,date_and_time,domain,domain_email,ip,url,anchor,title,description,keyword,keyphrase From links WHERE keyword = ? LIMIT $offset,$max";
$stmt = mysqli_stmt_init($conn);
if(mysqli_stmt_prepare($stmt,$query))
{
mysqli_stmt_bind_param($stmt,'s',$search);
mysqli_stmt_execute($stmt);
if($result = mysqli_stmt_get_result($stmt))
{
/*
FOLLOWING BOTH ARE EQUAL:
$col = mysqli_fetch_array($result) //SHORT VERSION.
$col = mysqli_fetch_array($result,MYSQLI_BOTH) //LONG VERSION.
*/
$col = mysqli_fetch_array($result); //SHORT VERSION.
$id = $col['0']; //MYSQLI_NUM
$date_and_time = $col['date_and_time']; //MYSQLI_ASSOC
$domain = $col['2']; //MYSQLI_NUM
$domain_email = $col['domain_email']; //MYSQLI_ASSOC
$ip = $col['4']; //MYSQLI_NUM
$url = $col['url']; //MYSQLI_ASSOC
$anchor = $col['6']; //MYSQLI_NUM
$title = $col['title']; //MYSQLI_ASSOC
$description = $col['8']; //MYSQLI_NUM
$keyword = $col['keyword']; //MYSQLI_ASSOC
$keyphrase = $col['10']; //MYSQLI_NUM
echo 'Id: ' .$id; echo '<br>';
echo 'Date And Time: ' .$date_and_time; echo '<br>';
echo 'Domain: ' .$domain; echo '<br>';
echo 'Domain Email: ' .$domain_email; echo '<br>';
echo 'Ip: ' .$ip; echo '<br>';
echo 'Url: ' .$url; echo '<br>';
echo 'Anchor: ' .$anchor; echo '<br>';
echo 'Title: ' .$title; echo '<br>';
echo 'Description: ' .$description; echo '<br>';
echo 'Keyword: ' .$keyword; echo '<br>';
echo 'Keyphrase: ' .$keyphrase; echo '<br>';
}
else
{
echo 'Record fetching failed!';
echo 'Error: ' .mysqli_stmt_error($stmt);
echo 'Error: ' .mysqli_stmt_errno($stmt);
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
echo '<b>'; echo __LINE__; echo '</b>'; echo '<br>';
//PAGINATION SECTION TO NUMBER THE PAGES AND LINK THEM.
$total_pages = ceil($row_count/$max);
$i = '1';
//$selfpage = $_SERVER['PHP_SELF'];
$selfpage = basename(__FILE__,''); //Echoes: url_encode_Template.php. Does not fetch the url $_GET params.
$path = rawurlencode($selfpage);
$query_string_1 = '?search=' .urlencode($search) .'&tbl=' .urlencode($tbl) .'&col=' .urlencode($col) .'&max=' .intval($max);
while($i<=$total_pages)
{
$query_string_2 = '&page=' .intval($i);
$url = $path .htmlentities($query_string_1) .htmlentities($query_string_2); //Full URL With $_GET params: https://localhost/Templates/url_encode_Template.php?search=keyword&tbl=links&col=keyword&max=100&page=1
if($page == $i)
{
echo '<a href=' .'"' .$url .'"' .'>' .'<b>' .intval($i) .'</b>' .'</a>';
}
else
{
echo '<a href=' .'"' .$url .'"' .'>' .intval($i) .'</a>';
}
$i++;
}
?>
Frankly, the pagination page is nearly finished, had it not been for this urlencode() issue!
If you spot any other errors which I have not asked about it's subject due to overlooking them then kindly show me a code sample by editing my code in order to show me how I really should've coded it. (I'm talking about my usage of urlencode(), rawurlencode(), htmlentities() as I'm trying to use them to prevent user's injecting unwanted html tags) to breakup my SERP.
I'd appreciate it if my code is edited by someone and the correction is displayed on this thread, wherever I went wrong.
Your problem is that you are overwriting the value of the $col variable that you initially populate with the 'col' parameter in the GET request with the result of your keyword search.
$col = $_GET['col']; //MySql Tbl Col to search.
...
$col = mysqli_fetch_array($result); //SHORT VERSION.
You do not seem to be using the col parameter for anything, you may be able to just remove it from the query string. If you do intend to use it, simply rename the variable you are using for the query result row.
For future reference, you can encode array values into a query string using the http_build_query function. This would simplify your code, and would have allowed you to see were the problem is in this case.
// Set some test values for the parameters
$search = 'my search term';
$tbl = 'my_table_name';
$col = 'column_1';
$max = 10;
// Simulate variable being overwritten with database result
$col = [
'id' => 123,
'date_and_time' => '2021-06-20 09:44:00',
'domain' => 'stackoverflow.com'
];
// Build an array of the parameters to be included in the query string
$queryParameters = [
'search' => $search,
'tbl' => $tbl,
'col' => $col,
'max' => $max
];
/*
* Build the query string using http_build_query
* Any array values will be represented appropriately
* Prepend the ? to the result
*/
$query_string_1 = '?'.http_build_query($queryParameters);
echo $query_string_1.PHP_EOL;

Get single row using mysqli from mysql db

I am trying to display a single row data using mysqli.
The query is
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
while($rowpwd = mysqli_fetch_array($getfield))
{
echo $rowpwd['name'];
}
}
if I print then i get
echo '<pre>';
print_r(mysqli_fetch_array($getfield));
echo '</pre>';
Array
(
[0] => abc
[name] => abc
)
But getting the name inside the while loop doesn't work.
Any help is highly appreciated.
Just try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield)['name'];
echo $rowpwd;
}
OR
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
{
$rowpwd = mysqli_fetch_array($getfield);
echo $rowpwd['name'];
}
Try this:
$getfield = mysqli_query($con,"select name from as_users where user_id=34");
if (mysqli_num_rows($getfield) > 0)
$whatYouWant = array();
{
while($rowpwd = mysqli_fetch_array($getfield))
{
//echo $rowpwd['name'];
$whatYouWant[] = $rowpwd['name'];
}
}
echo '<pre>';
print_r($whatYouWant);
echo '</pre>';
Change:
mysqli_fetch_array
To: If you want key of row
mysqli_fetch_assoc
To:If you want index of row
mysqli_fetch_row

How to pass array parameters in url - PHP

I'm tryng to pass parameters in the url, but I receive this error:
*implode(): Invalid arguments passed in *
I know that the cause is that I pass a string as parameter instead of an array, but how can I do to pass the array directly?
My code:
$all_prod_cat="SELECT * FROM products GROUP BY product_category";
$run_all_prod_cat = mysqli_query($con,$all_prod_cat);
$sql= "SELECT * FROM products";
if(isset($_GET['product_category']) && $_GET['product_category']!="")
{
$risperpag = 16;
$limit = $risperpag * $_GET['p'] - $risperpag;
$prod_cat = $_GET['product_category'];
$sql.=",categories WHERE product_category IN ('".implode("','",$prod_cat)."') AND product_category = cat_id LIMIT $limit,$risperpag";
$get_cat_pro_total = "SELECT * FROM products,categories WHERE product_category IN ('".implode("','",$prod_cat)."') AND product_category = cat_id";
$run_cat_pro_total = mysqli_query($con,$get_cat_pro_total);
$num_cat_pro_total = mysqli_num_rows($run_cat_pro_total);
$npag = ceil($num_cat_pro_total / $risperpag);
$p = $_GET['p'];
echo "<ul>";
if($p!=1)
{
echo '<li class="numPagine">← Indietro</li>';
}
for($i=1;$i<=$npag;$i++){
if($p==$i)
{
echo '<li class="numPagine pagina_attuale">'.$i.'</li>';
}
else
{
echo '<li class="numPagine">'.$i.'</li>';
}
}
if($p!=$npag)
{
echo '<li class="numPagine">Avanti →</li>';
}
echo "</ul>";
}
The problem is when I set the urlencode parameter, I tried to serialize, but I get an other error. I think I should unserialize, but I don't know the exact point.
Thanks in advance.
It is possible to generate url with get params using http_build_query function.
$urlparams = [
'product_category' => [
'cat1',
'cat2',
'cat3',
'cat4'
]
];
echo http_build_query($urlparams);

Populating dropdown list from database

I am trying to populate my dropdown list on a form with data from a database, i have tried the following but to no success it gives me an error saying unexpected ; i have tried removing but still getting errors?
echo form::label('myproduct', 'My Product:');
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"); while ($row = mysql_fetch_array($sql))
{echo "<option value=\"1\">" . $row['description'] . "</option>"; }
I think i could be putting the code in the wrong place as i have two php files, one is the controller, my code below:
public function action_claimincentive() {
$this->template->content = View::factory('crm/uk/claim_incentive_form');
$this->template->content->thanks = false;
$this->template->content->val = '';
$this->template->content->post = '';
if ($this->request->post('form')) {
$post = $this->request->post('form');
$stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`User Reference`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Acknowledgement No.`, `Product`)
VALUES (:userreference, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :product)');
$stmt->param(':userreference', $post['userreference']);
$stmt->param(':claimantpostcode', $post['claimantpostcode']);
$stmt->param(':orderno', $post['orderno']);
$stmt->param(':email', $post['email']);
$stmt->param(':storename', $post['storename']);
$stmt->param(':storetown', $post['storetown']);
$stmt->param(':dateofsale', $post['dateofsale']);
$stmt->param(':dateofdelivery', $post['dateofdelivery']);
$stmt->param(':acknowledgementno', $post['acknowledgementno']);
$stmt->param(':product', $post['product']);
try {
$stmt->execute();
$this->template->content->post = $post;
$this->template->content->thanks = true;
} catch (Exception $e) {
FB::error($e);
}
}
}
And the other is the actual form, see part of it below:
echo form::label('dateofdelivery', 'Date of Delivery:');
echo form::input('form[dateofdelivery]', $val, array('class'=>'input', 'id'=>'dateofdelivery'));
echo form::label('acknowledgementno', 'Acknowledgement No:');
echo form::input('form[acknowledgementno]', $val, array('class'=>'input', 'id'=>'acknowledgementno'));
echo form::label('product', 'Product:');
echo form::select('form[product]', array(
'' => 'Please select from the list',
'In store' => 'In store',
'Word of mouth' => 'Word of mouth',
'Television' => 'Television',
'Newspaper' => 'Newspaper',
'Magazine' => 'Magazine',
'Internet' => 'Internet',
'Google Reasearch' => 'Google Reasearch',
'Radio' => 'Radio',
'Medical Recommendation' => 'Medical Recommendation',
), '', array('class="select"', 'id'=>'product'));
echo form::submit('btnSubmit', 'Submit', array('id'=>'btnSubmit', 'class'=>'button'));
echo '</div>';
echo '<div class="clearfix"></div>';
echo form::close();
You have some errors in your markup, let's see:
In this line you have some errors:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive");
You are opening two parenthesis but only closing one should be something like:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"));
It's not necessary to assign the sql variable inside the method, any way I don't know which kind of framework are you using, so I am only noticing syntax errors.

Incorporating next/ previous in my 'foreach statement

I want to have a previous|next link on my page to change pictures.
I use a function to get relevent elements. However, I do not know what additional code is require in my function and where to place it. Also what should be in the html section.
I have looked at many pages on next/previous from 'foreach' but I cannot seem to relate to them.
Code:
function image_data($image_album_id) {
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
$query = mysql_query("SELECT $fields FROM `album_images`
WHERE `image_album_id`=$image_album_id AND `member_id`= '1'");
$ query_result = mysql_fetch_assoc($query);
foreach ($args as $field) {
$args[$field] = $query_result[$field];
}
return $args;
}
Html Page:
Last|
Next
</div>
<?php
$image_album_id =$_GET['image_album_id'];
$image_data = image_data($image_album_id, 'album_id', 'albumname', 'ext', 'timestamp');
echo '';
?>
<td class="smallfont albumthumb2" align="center" valign="middle" >
<img alt="" class="album_cover" src="<?php echo 'images/albums/thumbs/'. $image_data['album_id']. '/'. $image_album_id. '.' .$image_data['ext'];?> " height="175px" width="175px">
</td>
Many thanks. I hope I make sense.
Thanks for the speedy response.
Since there is a lot to look at and digest I thought I would just see if it works.
Alas no.
There is a parse error: syntax error, unexpected
'<' on line
$prev_link = Previous;
The only thing I notice within that section was an extra curly bracket after 'title="$prev_name"}'
I see there is the same for the 'title="$next_name"}'
WIth reference to your specific questions.
I get to the album_viewT page when I click on a link in a previous page. This contains tiny thumbnails. The link being localhost/Testing/album_view.php?artist_id=4&image_album_id=4 as an example.
Not sure if I fully understand "order of date is by image_album_data
Yes there are almost 3,000 rows in the database.
I should also mention that album_id has been replaced by artist_id.
Should the href be changed to "album_view.php/id/...
Your question lacks some data i.e. what is the page you are visiting that produces this code (the URL that is) and how is your data sorted. For instance I can see that you are providing potentially more information using the album_viewT.php? script but that is not necessarily the one that displays the HTML that you have produced.
So after all this I will make some assumptions and hopefully that will give you the right guidance to get to the solution.
I am assuming that your visiting page is http://mysite.com/albums/id/25
I am also assuming that the order of the data is by image_album_id.
Finally I am assuming that you have data in your db and I don't need to check whether there are returned data in the template for the current image. You will need to sort that out yourself.
You will need to get the data first from the database:
function image_data($image_album_id)
{
$results = array(
'previous' => FALSE,
'current' => FALSE,
'next' => FALSE,
);
$image_album__id = (int)$image_album_id;
$args = func_get_args();
unset($args[0]);
$fields = '`'.implode('`, `', $args).'`';
// Current record
$results['current'] = get_data(
$fields,
"AND image_album_id = {$image_album_id}"
);
// Previous - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['previous'] = get_data(
$fields,
"AND image_album_id < {$image_album_id} " .
"LIMIT 1"
);
}
// Next - no need to run this if we don't have a current
if ($results['current'])
{
// Current record
$results['next'] = get_data(
$fields,
"AND image_album_id > {$image_album_id} " .
"LIMIT 1"
);
}
// If all went well the $results array will contain the data
// for the 3 records. If we are at the beginning or the end,
// the previous and/or next will be FALSE
return $results;
}
function get_data($fields, $where = '')
{
$return = FALSE;
// Template
$template = "SELECT %s "
. "FROM album_images "
. "WHERE member_id = 1 %s";
// Current record
$sql = sprintf($template, $fields, $where);
$query = mysql_query($sql);
$query_result = mysql_fetch_assoc($query);
// If data has been found
if ($query_result)
{
$return = $query_result;
}
return $return;
}
For your HTML page:
<?php
$image_album_id = $_GET['image_album_id'];
$image_data = image_data(
$image_album_id,
'album_id', 'albumname', 'ext', 'timestamp'
);
$prev_link = '';
$next_link = '';
if ($image_data['previous'])
{
$prev_id = $image_data['previous']['album_id'];
$prev_name = $image_data['previous']['albumname'];
$prev_link = <a href="/albums/id/{$prev_id}" title="$prev_name"}>Previous</a>";
}
if ($image_data['next'])
{
$next_id = $image_data['next']['album_id'];
$next_name = $image_data['next']['albumname'];
$next_link = <a href="/albums/id/{$next_id}" title="$next_name"}>Next</a>";
}
$curr_id = $image_data['current']['album_id'];
$curr_ext = $image_data['current']['ext'];
?>
<?php echo $prev_link; ?>|<?php echo $next_link; ?>
</div>
<td class="smallfont albumthumb2" align="center" valign="middle">
<a href="album_viewT.php?images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}; ?>
<img alt="" class="album_cover"
src="images/albums/thumbs/
<?php echo "{$curr_id}/{$image_album_id}.{$curr_ext}"; ?>
height="175px"
width="175px" />
</a>
</td>
Note: I have split the line for the img and a tags in the HTML file for clarity.

Categories