Hello my fellow coding buddies.
I need some help, i've got this problem.
I have this database, and i want to retrive this data into my code via JS.
My database info:
create table datadatabase (
id int(10) not null AUTO_INCREMENT PRIMARY KEY,
name varchar(25) not null default '',
text longtext(25) not null default '',
image blob not null );
And i want the data into these fields.
<img src="<?php echo $img ?>"/>
<h3> <?php echo $text.','.$name ?> </h3>
But the problem is, the text & image is a slider and i want retrive new data everytime there is a function click on the "Next" button & the ID should be random so the first slides could be id 99 and the next slide could be 158 and so on.
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<img src"<?php echo $img ?>"/><h3> </h3>')
})
How should i approach this? AND Thanks you so much. :)
First of all, it is not a good practice to store images in databases, but if you want to do this you need to create a script that output an specific image from the db (i.e. by ID) and then output the raw data with the specific content-type. (I also recommend to insert the type of the image in one of the database fields).
url: /image.php?id=5
image.php
<?php
$id = isset($_GET['id'])?intval($_GET['id']):0;
$query = mysql_query("SELECT img FROM datadatabase WHERE id = '$id'");
$row = mysql_fetch_array($query);
if($type=="pjpeg")
$type="jpeg"; // the type could change depending on the database image type
header("Content-type:$type");
echo $row['image'];
?>
for the other fields , just read the database as usual. The result:
<img src="http://..../image.php?id=<?php echo $id ?>"/>
<h3> <?php echo $text.','.$name ?> </h3>
$('.Next').click(function(e) {
e.preventDefault();
Slide.appendSlide('<img src"http://..../image.php?id=<?php echo $id?>"/><h3> </h3>')
});
It is recommended as well implementing cache and image resizing before upload to avoid server payload.
There are others approaches like base64. I prefer by myself using the filesystem with image metadata instead of using only the database for image storage to make it scalable.
Insert.php :
$bin_string = file_get_contents($_FILES["file"]["name"]);
$mysqli->query("INSERT INTO upload(image) VALUES ('" . $bin_string . "')");
Retrieve.php?id=1 :
$result = $mysqli->query("SELECT * FROM upload id=1");
$output_bin_string = $result["image"];
header("Content-Type: image/png");
header("Content-Length: " . strlen($output_bin_string ));
echo $output_bin_string;
Access Via Js :
<img src="Retrieve.php?id=1" />
Related
I'm trying to dynamically add a new ACF repeater field value (course_slug) to the current user in Wordpress. The value to be added is a URL generated from a separate function.
If I use the following code on the original page using a static URL value for course_slug then the new value is added fine.
<?php $field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$current_user_id}");
echo $value;
$value[] = array("course_slug" => "http://www.exampleurl.com");
update_field( $field_key, $value, "user_{$current_user_id}");
?>
However if I run the code in a separate PHP file using two data values sent from the original page (as per below), then I receive a 500 error.
url: 'http://localhost:8888/wordpress/wp-content/themes/cookable/write-course-to-user.php',data:{"userIDdata":finaluserid, "courseURLdata":tidycourseurlupdate},
success: function(data) {
$('#result3').html(data);
}
});
write-course-to-user.php
<?php
$userIDfinal = isset($_REQUEST['userIDdata'])?$_REQUEST['userIDdata']:"";
$courseURLfinal = isset($_REQUEST['courseURLdata'])?$_REQUEST['courseURLdata']:"";
echo $userIDfinal;
echo $courseURLfinal;
echo "user_{$userIDfinal}";
$field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$userIDfinal}");
echo $value;
$value[] = array("course_slug" => $courseURLfinal);
update_field( $field_key, $value, "user_{$userIDfinal}");
?>
The three test echos in there display data as expected:
echo $userIDfinal; - displays 1
echo $courseURLfinal; - displays https://calendly.com/tjmdigital/cookable-1-week-1
echo "user_{$userIDfinal}"; displays user_1
Am I missing something daft here as to why the code will run fine in the original file but not in a linked one? Any advice hugely appreciated, thanks.
I have a form that currently is able to auto complete base on user input, it queries the MySQL database and successfully lists all possible matches in the table and give suggestions. Now I want to handle rows that do not exist. I am having trouble to get my PHP file to echo the error. Here is what I have so far:
I'm guessing in my auto search function in my javascript in main.php I need to return the error message to the page?
search.php
<?php
//database configuration
$host = 'user';
$username = 'user';
$password = 'pwd';
$name = 'name';
//connect with the database
$dbConnection = new mysqli($host,$username,$password,$name);
if(isset($_GET['term'])){
//get search term
$searchTerm = '%'.$_GET['term'].'%';
//get matched data from skills table
if($query = $dbConnection->prepare("SELECT * FROM nametbl WHERE name LIKE ? ORDER BY name ASC")) {
$query->bind_param("s", $searchTerm);
$query->execute();
$result = $query->get_result();
//$row_cnt = $result->num_rows;
//echo $row_cnt;
if($result -> num_rows){
while ($row = $result->fetch_assoc()) {
$data[] = $row['name'];
}
//return json data
echo json_encode($data);
mysqli_close($dbConnection);
}
else { echo '<pre>' . "there are no rows." . '</pre>'; }
}
else {
echo '<pre>' . "something went wrong when trying to connect to the database." . '</pre>';
}
}
?>
main.php
<div id="gatewayInput">
<form method="post">
<input type="text" id="name" name="name" placeholder="Name..."><br><br>
<?php
include("search.php");
?>
</div>
...
...
...
<script src ="../../../jqueryDir/jquery-3.2.1.min.js"></script>
<script src ="../../../jqueryDir/jquery-ui.min.js"></script>
<script type="text/javascript">
//auto search function
$(function() {
$( "#name" ).autocomplete({
source: 'search.php'
});
});
1.your method type is post in the form
in main.php
and in the search.php, you have used "if(isset($_GET['term'])){"
this needs to be fixed I guess. either both needs to be POST or GET.
Again you are using include method which the whole code in search.php will be made in-line and treated as a one file main.php. so you need not use GET or Post method.
How does get and Post methods work is
3.1) you have a html or PHP which submits the data from browser(main.php), and this request is being served by an action class(search.php)
example :- in main.php
3.2) now in search.php you can use something like if(isset($_POST['term'])){
You can use num_rows (e.g. if ($result -> num_rows)) to see if the query returned anything.
I am creating a website in which I need to sell products. I am stuck at the product page of the website.
The big e-commerce website like amazon.com must have a template of the product page and they dynamically load all the data including image of product, price, reviews from the database. I also want to create a similar product page where on clicking a link of product, it automatically loads all the images, price and info stored in the database and show it.
If another product is clicked, everything loads on that very same html/php template page and I don't have to make different page for different products. How can I do that?
I have been searching for a solution to this for many days, but I don't know what exactly to search for to get the answer.
Create a php page, say, load_products.php and pass get parameters like load_products.php?product_id=1.
Change the id (as per the database setup) and get the corresponding product details from database.
Edit : Detailed Answer
Database
Table: table_products
+--------------------------+---
| id | name | details | ...
+--------------------------+---
| 1 | Product1 | Details1 | ...
| 2 | Product2 | Details2 | ...
...
+--------------------------+---
I shall show you how it is done with MySQL database.
PHP Code
load_products.php
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$id=$row["id"];
$name=$row["name"];
echo "<a href='load_products?id=$id'>$name</a>";
}
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}
A really bare bones implementation, yet fully working and you can see the output on your localhost in 15 minutes. You can build on top of this.
You can search for : Loading images from database, javascript, jquery to enhance the website interface, using ajax on top of this and so on..
Please find the Improved version
products.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display All the Products
$res=mysql_query("SELECT * FROM table_products");
$productsPerRow = 4;
$columnWidth = (int)(100 / $productsPerRow);
$count = 0; //count product displayed
echo "<table>
<tr>";
while($row=mysql_fetch_array($res))
{
$count++;
$id = $row["id"];
$name = $row["name"];
$image = $row["image"]; //image name with extension, upload it in the images folder
echo "<td width='" . $columnWidth ."' >
<img src='images/" . $image ."' border='0'/><br />
<a href='load_product.php?id=$id'>$name</a>
</td>";
if($count%$productsPerRow==0)
echo"</tr><tr>";
}
//close empty cells
if ($count % $productsPerRow > 0) {
echo "<td colspan='" . ($productsPerRow - ($count % $productsPerRow)) .
"'> </td></tr>";
}
//close table
echo "</table>";
load_product.php page
// Establish connection to database
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('products_database_name');
// Display the details of a particular product based on the input click from user
if(isset($_GET["id"]))
{
$id=$_GET["id"];
$res=mysql_query("SELECT * FROM table_products WHERE id=$id");
echo "<table>";
while($row=mysql_fetch_array($res))
{
$details=$row["details"];
$name=$row["name"];
echo "<tr><td>$name</td><td>$details</td></tr>";
}
echo "</table>";
}
I'm trying to get records from the database using a client side (Javascript) clickable list. The problem is that I want the clickable links to be sourced from the data in the database in the first place (MySQL).
I'm having problems passing the data to create the clickable list. I've tried various ideas and hit stumbling blocks to do with client side and server side programming (and briefly looked into JQuery but it appears difficult to do). I've been attempting this with HTML, PHP, Javascript, JQuery (briefly) and MySQL.
So I need to SELECT post_id, post_title FROM posts and make post_title clickable in the list but using the associated post_id to find the relevant data in the DB and post this via innerHTML into another element. Any ideas?
index.php <- List
<html>
<head>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<?php
$sql = 'SELECT post_id AS "id", post_title AS "title" FROM posts';
$posts = $mysqli->query($sql);
?>
<ul id="post_list">
<?php
foreach ($posts as $post) {
?>
<li><a href="#" data-id="<?php echo $post['id'] ?>"><?php
echo $post['title']
?></a></li>
<?php
}
?>
</ul>
<div id="post_content"></div>
</body>
</html>
script.js <- Interactivity (requires jquery)
$(document).ready(function() {
$('#post_list').on('click', 'li a', function() {
$('#post_content').load('get_post.php?id=' + $(this).data('id'));
});
});
get_post.php <- Selected post
<?php
if (!empty($_GET['id'])) {
$sql = 'SELECT * FROM posts WHERE post_id = '.$_GET['id'].'';
$res = $mysqli->query($sql);
if (($post = $res->fetch_assoc())) {
?>
<h1><?php echo $post['post_title'] ?></h1>
<p><?php echo $post['post_body'] ?></p>
<div class="pull-right"><?php echo $post['post_author'] ?></div>
<?php
} else {
header("HTTP/1.0 404 Not Found");
die();
}
}
?>
Maybe I've not understand correctly, but this can solve your problem :
You need at least 2 files (3 if you separate the Js Code)
Index.php :
$arrayItems = array()//The array containing your datas from the database
echo '<div id="listItems">';
for($i = 0; $i < count($arrayItems); $i++){
echo '<div class="item" idFromDB="'.$arrayItems[$i]['post_id'].'">'.$arrayItems[$i]['post_title'].'</div>';
}
echo '</div>';
echo '<div id="containerDetailsItem"></div>';
javascript.js : (which is more Jquery)
$(document).ready(function() {
$('.item').live('click', function(){
$('#containerDetailsItem').load('myAjax.php?idItem='+$(this).attr('idFromDB'));
});
});
and the ajax File (myAjax.php) :
if(isset($_GET['idItem']) && $_GET['idItem'] != ''){
$idItem = (int)$_GET['idItem'];
//Get the infos from the database with the ID given
echo 'datas from BDD';
}
And I think that will do what you need. This is simple PHP with Jquery and Ajax.
PS : There is just minified code. You'll need to include Jquery (from google maybe) and to make the link between index.php and Javascript.js
I'm not sure if this question is possible but what I want is to take a set of photos from Flickr and dump every url into a file (text is fine). Dumping them within anchor tags would be plus. So far I've seen this and I looked through the Galleria viewers JavaScript code but no luck. I'm expecting a simple few lines of code to do this because Galleria does it but I'm not really sure where in their code Flickr is accessed to get the image urls.
I think this might be the answer actually but if someone else comes along and has another answer I'll of course accept theirs instead of just mine.
It seems that phpflickr has this example which should work:
<?php
require_once("phpFlickr/phpFlickr.php");
// Create new phpFlickr object
$f = new phpFlickr("[API Key]");
$f->enableCache(
"db",
"mysql://[username]:[password]#[server]/[database]"
);
$i = 0;
if (!empty($_POST['username'])) {
// Find the NSID of the username inputted via the form
$person = $f->people_findByUsername($_POST['username']);
// Get the friendly URL of the user's photos
$photos_url = $f->urls_getUserPhotos($person['id']);
// Get the user's first 36 public photos
$photos = $f->people_getPublicPhotos($person['id'], NULL, NULL, 36);
// Loop through the photos and output the html
foreach ((array)$photos['photos']['photo'] as $photo) {
echo "<a href=$photos_url$photo[id]>";
echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "Square") . ">";
echo "</a>";
$i++;
// If it reaches the sixth photo, insert a line break
if ($i % 6 == 0) {
echo "<br>\n";
}
}
}
?>
<h3>Enter a username to search for</h3>
<form method='post'>
<input name='username'><br>
<input type='submit' value='Display Photos'>
</form>
<p>View Source</p>