Php storing url image path in MySQL DB - php

I am trying to store URL Image paths into MySQL DB. But i am not getting any results with my code.
Why is it not storing anything?
Would it be better just to store the image name or the entire path?
target example: "www.example.com/medium/imagename.jpg"
Table Name: urlimage
id: autoincrement
image_name
Php code for inserting data into DB
<?php
$images = explode(',', $_GET['i']);
$path = Configuration::getUploadUrlPath('medium', 'target');
if(is_array($images)){
$objDb = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$objDb->exec('SET CHARACTER SET utf8');
$sql = "INSERT INTO `urlImage` (`image_name`) VALUES ";
foreach ($images as $image) {
//echo '<div><p>' . $path . $image . '</p><img src="' . $path . $image . '" /></div>';
$value[] = "(".$path.$image.")"; // collect imagenames
}
$sql .= implode(',', $value).";"; //build query
$objDb->query($sql);
}
?>

Try this; it may work:
$value[] = "('".$path.$image."')";

you have error in $sql
it must be $value[] = "('".$path.$image."')";
debug with
echo "<pre>"; print_r($sql);echo "</pre>";
and if your using PDO function then call
prepare->execute

Related

Json data getting read but not inserting into mysql using php

Im trying to insert json data using php into mysql,
I get success msg, but no records are inserted.
My json data is :
jsondata.json:
{"users": { "bert":6.44, "earnie":0.25, "bigbird":34.45 }}
My php code:
<?php
//First: read data
$fo=fopen("data.json","r");
$fr=fread($fo,filesize("data.json"));
$array=json_decode($fr,true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//To display all values from JSON file
echo '<pre>';print_r($array);
//Save to DB
$hostname = 'localhost';
$username = 'root';
$password = '';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />';
//$count = $dbh->exec("INSERT INTO USERSAMOUNTS(USERNAME, AMOUNT) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
$count = $dbh->exec("INSERT INTO json(firstName) VALUES " . $values) or die(print_r($dbh->errorInfo(), true));
echo $count;// echo the number of affected rows
$dbh = null;// close the database connection
echo 'Success<br />';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I believe the problem could be the order in which the actions are performed.
<?php
//First: read data
$fo = fopen("jsondata.json", "r");
$fr = fread($fo, filesize("jsondata.json"));
$array = json_decode($fr, true);
//Second: create $values
$rows = array();
foreach ($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
//Third: display
echo '<pre>';
print_r($array);
//Fourth: save to db
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
echo 'Connected to database<br />'; // echo a message saying we have connected
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
echo $count; // echo the number of affected rows
$dbh = null; // close the database connection
echo 'Success<br />';
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
Enables or disables emulation of prepared statements. Some drivers do not support native prepared statements or have limited support for them for more info please check - http://php.net/manual/en/pdo.setattribute.php
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$count = $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $values);
Hope this help.
The issue is with how your are trying to insert data. I'm surprised you're not getting an error.
You should use a prepared statement. See the following... https://stackoverflow.com/a/4629088/2033178
Some things are funky here.
At first it looks like you're expecting the data to come magically from $data (unless that is passed somewhere?)
$array = json_decode($data, true);
$rows = array();
foreach($array['users'] as $key => $value)
$rows[] = "('" . $key . "', '" . $value . "')";
$values = implode(",", $rows);
And then it looks like you're opening a file and parsing the JSON (but not doing the above magic with $rows[])
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
Why not insert on the for each loop?
$fo=fopen("jsondata.json","r");
$fr=fread($fo,filesize("jsondata.json"));
$array=json_decode($fr,true);
$count = 0;
$dbh = new PDO("mysql:host=$hostname;dbname=nodejs", $username, $password);
try {
foreach($array['users'] as $key => $value)
$count = $count + $dbh->exec("INSERT INTO USERAMOUNTS(USERNAME, AMOUNT) VALUES " . $key . " " . $value . ")";
} catch ...

display img mysqli php - How can i solve it?

i am training to add and display the img from the database, but i cant display the img from the database
i have used this code .. How can i solve it?
<?php
$conn = #mysqli_connect("localhost", "root", "");
if ($conn) {
$db = mysqli_select_db($conn, "name_of_db");
}
$query = mysqli_query($conn, "SELECT * FROM Table_name");
while ($row = mysqli_fetch_object($query)) {
$ID = $row->ID;
$adi = $row->adi;
$adres = $row->adres;
$te11 = $row->Tel1;
$tel2 = $row->Tel2;
$TC = $row->TC;
$Pasaport = $row->Pasaport;
$Para = $row->Para;
$Odedi = $row->Odedi;
$foto = $row->fotograf;
$Mekkeotel = $row->Mekkeotel;
$Medineotel = $row->Medineotel;
echo '<img src="' . $row->field_name_of_photo_in_db . '" border=0>';
}
?>
You would recommend you not assigning all the information to separe variables, because it doesn't make any difference. You are just increasing your typing and you are basically losing more time. As for your question, change
echo '<img src="' . $row->field_name_of_photo_in_db . '" border=0>';
to
echo '<img src="' . $row->fotograf . '" border=0>';
and it should work fine now.

Add code around one particular result from SELECT statement

I have the following code SELECTING the Title and Image from the "Courses" table in my database.
<?php
$username = 'REMOVED';
$password = 'REMOVED';
try {
$conn = new PDO('mysql:host=localhost;dbname=REMOVED', $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Title, Image FROM Courses');
$stmt->execute();
while($row = $stmt->fetch()) {
print_r($row);
}
}
catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
?>
How can I make it so that the Title has a header tag wrapped around it and the Image is inside of an image src=""?
depending on your PDO settings the result may for example be returned in an associative array (which would be the most common default setting):
while($row = $stmt->fetch()) {
echo '<img src="' . $row["Image"] . '" title="' . $row["Title"] . '">';
}
update: to force the fetching of associative array, just replace $stmt->fetch() with $stmt->fetch((PDO::FETCH_ASSOC)
replace while loop with following code:
$string="<header>";
$imagesrc="";
While($row=$stmt->fetch()){
$string+=$row['Title'];
$imagesrc=$row['Image'];
}
$string+="</header>";
$stringImage="<img src='".$imagesrc."' />";

How can I retrieve data from MySQL table and insert it into QR code using PHP?

I have this PHP code that creates a QR code with the given data:
<?php
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$tempDir = JPATH_SITE . '/images/';
$codeContents = 'This Goes From File';
$fileName = 'qr_'.md5($codeContents).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($codeContents, $pngAbsoluteFilePath);
}
else {
echo "Not working!";
}
echo '<img src="'.$urlRelativeFilePath.'" />';
?>
What we need is to connect to a MySQL table (#__rsforms_submissions), retrieve some fields (for example, Name and Mail, Phone) and insert them in the QR code instead of the data provided by the example. To do so I would retrieve the logged in user's user
$user = JFactory::getUser();
$username = JUserHelper::getUsername($user->id);
Then, the MySQL query would look something like
SELECT Name,Mail, Phone FROM #__rsforms_submissions WHERE Username = $username
However, what's next? How do I insert these values into the PHP code?
Thanks!
Dani
I'm assuming you are using Joomla. I don't know Joomla, but as I can figure it out from selecting and retrieving SQL data:
<?php
/* get username */
$user = JFactory::getUser();
$username = JUserHelper::getUsername($user->id);
/* get data from database */
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "custom.".
// Order it by the ordering field.
$query->select($db->quoteName(array('Name', 'Mail', 'Phone')));
$query->from($db->quoteName('#__rsforms_submissions'));
$query->where($db->quoteName('Username') . ' LIKE '. $db->quote('\'' . $username . '\''));
$query->order('ordering ASC');
// Reset the query using our newly populated query object.
$db->setQuery($query, 0, 1); // 0 = start, 1 = number of records
$row = $db->loadRow();
/* create the qrcode */
include(JPATH_LIBRARIES . '/phpqrcode/qrlib.php');
$tempDir = JPATH_SITE . '/images/';
$codeContents = $row->Name . ', ' . $row->Mail . ', ' . $row->Phone . ', '; // this is what goes into qrcode
$fileName = 'qr_'.md5($codeContents).'.png';
$pngAbsoluteFilePath = $tempDir.$fileName;
if (!file_exists($pngAbsoluteFilePath)) {
QRcode::png($codeContents, $pngAbsoluteFilePath);
$urlRelativeFilePath = JUri::root() .'images/' . $fileName;
echo '<img src="'.$urlRelativeFilePath.'" />';
}
else {
echo "Not working!";
}
Note: It's not tested! However, it should give you an idea about how to do it.

Save CSV files into mysql database

I have a lot of csv files in a directory. With these files, I have to write a script that put their content in the right fields and tables of my database. I am almost beginner in php language : I have found some bits of code on the Internet. It seems to work, but I am stuck at a stage. Some topics are related on this website, but I did not found the ecat problem.
I have written a php script that permits to get the path and the name of these files. I managed too to create a table whose name depends of each csv (e.g : file ‘data_1.csv’ gives the table data_1.csv in my-sql). All the tables have the three same fields, id, url, value.
The last thing to do is to populate these tables, by reading each file and put the values separated by ‘|’ character in the right tables. For example, if a line of ‘data_1.csv’ is
8756|htttp://example.com|something written
I would like to get a record in data_1.csv table where 8756 is in id, htttp://example.com in url field, and something written in value field.
I have found the way to read and print these csv with fcsvget function. But I do not know how to make these lines go into the SQL database. Could anyone help me on this point?
Here is my script below
<?php
ini_set('max_execution_time', 300);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass, true) or die ('Error connecting to mysql');
$dbname = 'test_database';
mysql_select_db($dbname);
$bdd = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
else {
echo "hello <br>";
}
$dir = 'C:\wamp\www\test';
$imgs = array();
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (!is_dir($file) && preg_match("/\.(csv)$/", $file)) {
array_push($imgs, $file);
}
}
closedir($dh);
} else {
die('cannot open ' . $dir);
}
foreach ($imgs as $idx=>$img) {
$class = ($idx == count($imgs) - 1 ? ' class="last"' : '');
$filePath=$dir . '\\'. $img;
$file = fopen($filePath, "r") or exit("Unable to open file!");
$nom = 'FILE: ' . $dir . '\\'. $img;
echo $nom;
settype($nom, "string");
echo '<br>';
$chemin = '<img src="' . $dir . $img . '" alt="' .
$img . '"' . $class . ' />' . "\n";
echo $chemin;
$file_name = basename($filePath);
$sql = 'CREATE TABLE `' . $file_name . '` (id int(20000), url varchar(15), value TEXT)';
mysql_query($sql,$conn);
$handle = fopen($filePath, 'r');
while (($row = fgetcsv($handle)) !== false) {
foreach ($row as $field) {
echo $field . '<br />';
}
}
fclose($handle);
}
echo ("VERIFY");
for ($i = 1; $i <= 1682; $i++) {
echo ("<br>A : " . $i);
$checkRequest= "select * from movies where movieID='". $i."'";
echo ("<br>". $checkRequest);
if ($result = $mysqli->query($checkRequest)) {
printf("<br> Select ". $i ."returned %d rows.\n", $result->num_rows);
if ($result->num_rows == 0) {
echo ("I : " . $i);
}
$result->close();
}
}
$mysqli->close();
?>
MySQL provides a wonderful feature that allows you to import a CSV file directly, in a single query.
The SQL command you're looking for is LOAD DATA INFILE
Manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html
Quick example:
LOAD DATA INFILE 'fileName'
INTO TABLE tableName
FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
(
field1,
field2,
field3,
#variable1,
#variable2,
etc
)
set
(
field4 = concat(#variable1,#variable2)
);
That's a fairly basic example, but it covers most of what you'd want. The manual page gives full details of how to do some very complex stuff with it.
Hope that helps.
after
foreach ($row as $field) {
echo $field . '<br />';
You need to parse the result after ; like:
$pieces = explode(";", $field);
and then insert every piece into the database
$sql = ' INSERT INTO X VALUES ("'.$pieces[0].'","'.$pieces[1].'","'.$pieces[2].'","'.$pieces[3].'","'.$pieces[4].'")';
mysql_query($sql, $conn);
Also mysqlimport can be used
private function runImport($host, $username, $password, $schema, $csvFilePath) {
$output = array();
$cmd = "/usr/bin/mysqlimport --host=$host";
$cmd .= ' --fields-terminated-by=\',\' --fields-optionally-enclosed-by=\'"\' ';
$cmd .= ' --user=' . $username . ' --password='. $password;
$cmd .= " $schema $csvFilePath";
exec($cmd, $output, $retVal);
foreach ($output as $line) {
echo "$line\n";
}
echo "\n\nReturn code : $retVal";
}

Categories