how to get wordpress post with by category with images - sql

I have installed wordpress and opencart in same database. Trying to get wordpress posts table inside opencart module. got the mysql query to fetch all information except image. I dont why images are different from the post in loop of result. Kindly guide, following is the code.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "tablename";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {die("Connection failed: " . $conn->connect_error);}
$sql = "SELECT * FROM wp_posts WHERE post_type = 'attachment' ORDER BY ID DESC LIMIT 3";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<div class="col-sm-4">';
echo "Post ID: " . $row["ID"] . " / ";
echo "Post Title: " . $row["post_title"] . " / ";
echo "Post Title: " . $row["post_date"] . " / ";
echo '<img src="' . $row['guid'] . '" class="img-responsive">';
echo '</div>';
}
} else {
echo "0 results";
}

Run your query in phpMyAdmin and check if result you got is the same as you want (you get those pictures that you want).
Then I advise you to set the checkpoint inside the loop and look at the data. Debugging is a very powerful thing in finding errors, it's time to start using it

Related

duplication of products in prestashop backend and front

I have imported 16 000 products, and now I have 57 000 products.
Can any one help me please to delete all duplicated products as you see in picture.
Product with different id and same reference.
Image backoffice:
Image front:
You can try something like that, you can test it in development environment, you should create a php file in your root project.
require_once('config/config.inc.php');
require_once('init.php');
$query = "select id_product,reference from " . _DB_PREFIX_ . "product where active=1";
$res = Db::getInstance()->ExecuteS($query);
foreach($res as $prod){
$query = "select id_product from " . _DB_PREFIX_ . "product where reference=$prod['reference']";
$res = Db::getInstance()->ExecuteS($query);
$count = count($res);
if($count){
foreach ($res as $key => $p) {
if (--$count <= 0) {
// to not delete the last occurrence for a given reference
break;
}
$id_product = $p['id_product'];
$product = new Product((int)$id_product);
if($product->delete())
echo 'product '.$id_product.' is deleted';
}
}
}

SQL being a jerk again

I have the script I use that displays things from a table in my database, but it keeps giving me this error:
Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\raynerblogger1\posts.php on line 21
someone please help
$sql = "SELECT * FROM blogs;";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div id='message'>";
echo $row['author']; echo(':') . "<br>";
echo $row['post'] . "</div>" . "<br>" . "<br>" . "<br>";
}
Try this, I edited line 1 and 6:
$sql = "SELECT * FROM blogs";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div id='message'>";
echo $row['author'].":". "<br>";
echo $row['post'] . "</div>" . "<br>" . "<br>" . "<br>";
}

PDO bind variables to prepared mysql statement and fetch using while loop

I've used several of your guides but I can not get the following to run. If I hardcode the 2 variables in the Select statement it runs fine. I need to use variables, and I can't get the bind statement to work. Plenty of experience with the old Mysql_ but the PDO is still a challenge at this point.
$db_table = "ad";
$ID = "1";
$dsn = "mysql:host=$hostname;dbname=$database;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $username, $password, $opt);
$result = $pdo->prepare("SELECT * FROM :ad WHERE id= :id "); // Line 359
$result->bindParam(':ad', $db_table, PDO::PARAM_STR);
$result->bindParam(':id', $ID, PDO::PARAM_STR);
$result->execute();
while($row = $result->fetch(PDO::FETCH_ASSOC))
{
$product = $row["product"];
$msrp = $row["msrp"];
$sale = $row["sale"];
$content = $row["content"];
echo "<strong>$product</strong> - $content<br />";
// echo $msrp . "<br />";
if($msrp != "0.00") { echo "MSRP $$msrp"; }
if($sale != "0.00") { echo "<img src='/images/c.gif' width='75' height='6' border='0'><span style='color: red;'>Sale $$sale</span>"; }
}
$pdo = null;
The above generates this error,
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '? WHERE id=?' at line 1' in
/XXXXXXXXXXXX/index_desktop_pdo.php:359
Your database structure is wrong. There should be always only one table to hold all the similar data. And therefore no need to make a variable table name.
To distinguish different parts of data just add another field to this table. This is how databases work.
So your code should be
$section = "ad";
$ID = "1";
$result = $pdo->prepare("SELECT * FROM whatever WHERE section=:ad AND id= :id");
$result->bindParam(':ad', $section);
$result->bindParam(':id', $ID);
$result->execute();

How to save a date from php to SQL table?

i have a php file that works OK.
That php makes recursive search in a local folder, and calculates the last modification DATE of those files.
My question: Every time that i open that php file i want that date to be stored in a SQL table.
-i have created a table with 2 columns (ID, date) where ID=1 then go and update the date field.
but how can i call FROM php file to save the date into sql field?
My php file:
<?php
// LAST FILES UPDATE
function getAllFiles($directory, $recursive = true) {
$result = array();
$handle = opendir($directory);
while ($datei = readdir($handle))
{
if (($datei != '.') && ($datei != '..'))
{
$file = $directory.$datei;
if (is_dir($file)) {
if ($recursive) {
$result = array_merge($result, getAllFiles($file.'/'));
}
} else {
$result[] = $file;
}
}
}
closedir($handle);
return $result;
}
function getHighestFileTimestamp($directory, $recursive = true) {
$allFiles = getAllFiles($directory, $recursive);
$highestKnown = 0;
foreach ($allFiles as $val) {
$currentValue = filemtime($val);
if ($currentValue > $highestKnown) $highestKnown = $currentValue;
}
return $highestKnown;
}
echo '<div align="center" style=" padding-top:5px; margin-top:5px; border-top:dotted #777; border-width:1px;">Last Update Date:<br>';
date_default_timezone_set('Europe/Athens');
setlocale(LC_ALL, array('el_GR.UTF-8','el_GR#euro','el_GR','greek'));
echo strftime('%d %b %Y, %H:%M:%S', getHighestFileTimestamp('../'));
echo '</div>';
$host="localhost"; // Host name
$username="..."; // Mysql username
$password="..."; // Mysql password
$db_name="..."; // Database name
$tbl_name="..."; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// update data in mysql database
$sql="UPDATE $tbl_name SET date='HUMMMM HERE HOW TO PULL THE VALUE?' WHERE id='1'";
$result=mysql_query($sql);
// if successfully updated.
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
Try something like this:
// use the function to calculate highest timestamp
$highestdate = getHighestFileTimestamp("../");
// Insert the highest timestamp into the db
$sql= sprintf("UPDATE $tbl_name SET date='%s' WHERE id='1'",
$highestdate);
--EDIT-- merged with Hiroto's answer
You can use these other styles to concatenate string constants with variables
$sql = "UPDATE {$tbl_name} SET date='{$date}' WHERE id='{$id}';";
Or, you could use concatenation.
$sql = "UPDATE " . $tbl_name . " SET date='" . $date . "' WHERE id='1';";
$sql = "UPDATE {$tbl_name} SET date='{$date}' WHERE id='{$id}';";
Or, you could use concatenation.
$sql = "UPDATE " . $tbl_name . " SET date='" . $date . "' WHERE id='1';";

shopping cart to email

I use simplecartjs to make a shopping cart on my website where you can select element and send it to your cart... next step, will be the checkout process, but for business reason, no checkout process will append, and a simple form with name and email and date for order pickup will be ask. Now the order must be send to an email address (at the company) that will fullfill the order.
The question : how to send the content of the cart to an email body or as attachement ?
This Will add the email order, suplimentary fields to the user "Phone and Adress",
Check during the CheckOut the the user is registered if not will redirect to registration.
WILL CLEAR Shopping cart only after succesful email order sent.
Will send 2 e-mail to the shop owner "shop#domain.com" and to the users email so he sees the order
Will need to make a new page for the Thank You part after succesful order is made
simplecartjs: around line 288 is in mine
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
sendjs.php
<?php require( dirname(__FILE__) . '/wp-load.php' );
/* cheking is user is logged in*/
if ( is_user_logged_in() ) {
get_currentuserinfo(); /* getting user details*/
/* sending e-mail to the shop email */
$to = 'shop#domain.com';
$subject = 'New Order';
$jcitems = " Name: " . $current_user->user_lastname .
" \n First Name: " . $current_user->user_firstname .
" \n Email: " . $current_user->user_email .
" \n Phone: " . $current_user->phone .
" \n Adress: " . $current_user->adress ;
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/* sending e-mail with the order to the users email*/
$to = $current_user->user_email;
$subject = 'Order copy from Domain';
$jcitems = "Thank you for you order. Below you have your ordered products".
" \n ORDER: \n\n " . $_POST['jcitems'] . "Total: " . $_POST['jctotal'] . " USD" .
"\n\n http://www.domain.com \nshop#domain.com";
$headers = 'From: shop#domain.com' . "\r\n" .
'Reply-To: shop#domain.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
/*Clearing the cart info after succesfull order is made*/
setcookie ("simpleCart", "", time() - 3600);
/*redirecting user to Thank you page from Wordpress*/
Header('Location: http://www.domain.com/thank_you/'); }
else { /*sending user to register*/
header( 'Location: http://www.domain.com/wp-login.php?action=register' ) ; exit; } ?>
You will need Register Plus plugin for wordpress to add the extra 2 fiels to the user "phone and address"
be sure to check
Add Registration Field
Add Profile Field
Required
You should add new checkout method to simplecartjs:
me.emailCheckout = function() {
itemsString = "";
for( var current in me.items ){
var item = me.items[current];
itemsString += item.name + " " + item.quantity + " " + item.price + "\n";
}
var form = document.createElement("form");
form.style.display = "none";
form.method = "POST";
form.action = "sendjs.php";
form.acceptCharset = "utf-8";
form.appendChild(me.createHiddenElement("jcitems", itemsString));
form.appendChild(me.createHiddenElement("jctotal", me.total));
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
This will create new form element and submit cart data to sendjs.php. Enable this checkout method by setting me.checkoutTo = 'Email' in simplecart options.
Now create a new sendjs.php file:
<?php
$to = 'you#example.com';
$subject = 'the subject';
$jcitems = $_POST['jcitems'];
$headers = 'From: webmaster#example.com' . "\r\n" .
'Reply-To: webmaster#example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $jcitems, $headers);
Header('Location: thankyou.html');
?>
This will send the email message and redirect to thankyou.html page you should also create.