I have a lot of links which has JSON data inside and i need the data from links to mysql, what could be fastest way for that ?
Is it possible to modify this code below to make it able to read from multiple urls ?
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
//read the json file contents
$jsondata = file_get_contents('empdetails.json');
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
?>
Here is an example of reading url's from a excel file.
I am using http://code.google.com/p/php-excel-reader/.
File - urls.xls.
It assumes this excel contains url's in the first column.
<?php
//connect to mysql db
$con = mysql_connect("username","password","") or die('Could not connect: ' . mysql_error());
//connect to the employee database
mysql_select_db("employee", $con);
$data = new Spreadsheet_Excel_Reader("urls.xls",false);
$rows = $data->rowcount(0);
for( $i=0;$i<$rows;$i++ ) {
//read the json file contents
$jsondata = file_get_contents($data->val($i,0));
//convert json object to php associative array
$data = json_decode($jsondata, true);
//get the employee details
$id = $data['empid'];
$name = $data['personal']['name'];
$gender = $data['personal']['gender'];
$age = $data['personal']['age'];
$streetaddress = $data['personal']['address']['streetaddress'];
$city = $data['personal']['address']['city'];
$state = $data['personal']['address']['state'];
$postalcode = $data['personal']['address']['postalcode'];
$designation = $data['profile']['designation'];
$department = $data['profile']['department'];
//insert into mysql table
$sql = "INSERT INTO tbl_emp(empid, empname, gender, age, streetaddress, city, state, postalcode, designation, department)
VALUES('$id', '$name', '$gender', '$age', '$streetaddress', '$city', '$state', '$postalcode', '$designation', '$department')";
if(!mysql_query($sql,$con))
{
die('Error : ' . mysql_error());
}
}
?>
Hope this helps.
Related
I have large MySQL database on production (14 GB). Sometimes I have to download it and work on it locally. This is of course problem. The database have 10 tables with field "date" and 5 tables without field "date".
Is there any easy way to download it for the last month? 10 tables with condition "data > '2020-07-24'" and full 5 other tables. I would like to dump it into one .sql file and next import it locally.
Unfortunately the database has some relations between 10 tables...
Try this code and its must be to create columns CREATED_DATE with any tables
i hope it will work :)
if you need AutoBackup with GoogleDrive
https://github.com/engacs/Autobackup-databse-to-GoogleDrive/
<?php
// ini_set('memory_limit', '1024M');
// User home directory (absolute)
$homedir = "backup/"; // If this doesn't work, you can provide the full path yourself
// Site directory (relative)
$sitedir = "";
// Base filename for backup file
$fprefix = "sitebackup-";
// Base filename for database file
$dprefix = "dbbackup-";
// MySQL username
$dbuser = "root";
// MySQL password
$dbpass = "";
// MySQL database
$dbname = "";
// MySQL Host
$host = "localhost";
// Get connection object and set the charset
$conn = mysqli_connect($host, $dbuser, $dbpass, $dbname);
$conn->set_charset("utf8");
// Get All Table Names From the Database
$tables = array();
$sql = "SHOW TABLES";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
$sqlScript = "";
foreach ($tables as $table) {
// Prepare SQLscript for creating table structure
$query = "SHOW CREATE TABLE $table";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$sqlScript .= "\n\n" . $row[1] . ";\n\n";
$form_date='2020-08-01'; // Split From Date
$to_date='2020-08-31'; // Split to Date
$query = "SELECT * FROM $table "; //
// if you whant to use Split the database by date
// $query .=" WHERE CREATED_DATE >= DATE(CONCAT_WS('-', '2020', '08', '01')) AND CREATED_DATE < DATE(CONCAT_WS('-', '2020', '08', '31'))"
// $query .=" WHERE CREATED_DATE >= '$form_date' AND CREATED_DATE < '$to_date' ";
$result = mysqli_query($conn, $query);
$columnCount = mysqli_num_fields($result);
// Prepare SQLscript for dumping data for each table
for ($i = 0; $i < $columnCount; $i ++) {
while ($row = mysqli_fetch_row($result)) {
$sqlScript .= "INSERT INTO $table VALUES(";
for ($j = 0; $j < $columnCount; $j ++) {
$row[$j] = $row[$j];
if (isset($row[$j])) {
$sqlScript .= '"' . $row[$j] . '"';
} else {
$sqlScript .= '""';
}
if ($j < ($columnCount - 1)) {
$sqlScript .= ',';
}
}
$sqlScript .= ");\n";
}
}
$sqlScript .= "\n";
}
if(!empty($sqlScript))
{
// Save the SQL script to a backup file
$backup_file_name = $homedir.$dprefix.$dbname . '_' . $uid . '.sql';
$fileHandler = fopen($backup_file_name, 'w+');
$number_of_lines = fwrite($fileHandler, $sqlScript);
fclose($fileHandler);
}
Yes, look at mysqldump's --where option.
I Maintain 4 tables.
Table 1(table name: products)-> pro_id, pro_model, price
Table 2(table name: pro_description)-> id, pro_id, pro_name, pro_desp
Table 3(table name: pro_to_category)-> id, pro_id, cat_id
Table 4(table name: category)-> cat_id, cat_desp
Now I wants to download the fields, when I export mysql data to excel
download, pro_id, pro_name, pro_desp, price, pro_model, category
(notes: category needs the cat_desp, no need cat_id)
Thanks for advance. help me to solve. :(
<?php
/*******EDIT LINES 3-8*******/
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "username"; //MySQL Username
$DB_Password = "password"; //MySQL Password
$DB_DBName = "databasename"; //MySQL Database Name
$DB_TBLName = "tablename"; //MySQL Table Name
$filename = "excelfilename"; //File Name
/*******YOU DO NOT NEED TO EDIT ANYTHING BELOW THIS LINE*******/
//create MySQL connection
$sql = "Select * from $DB_TBLName";
$Connect = #mysql_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysql_error() . "<br>" . mysql_errno());
//select database
$Db = #mysql_select_db($DB_DBName, $Connect) or die("Couldn't select database:<br>" . mysql_error(). "<br>" . mysql_errno());
//execute query
$result = #mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
$file_ending = "xls";
//header info for browser
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*******Start of Formatting for Excel*******/
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
//start of printing column names as names of MySQL fields
for ($i = 0; $i < mysql_num_fields($result); $i++) {
echo mysql_field_name($result,$i) . "\t";
}
print("\n");
//end of printing column names
//start while loop to get data
while($row = mysql_fetch_row($result))
{
$schema_insert = "";
for($j=0; $j<mysql_num_fields($result);$j++)
{
if(!isset($row[$j]))
$schema_insert .= "NULL".$sep;
elseif ($row[$j] != "")
$schema_insert .= "$row[$j]".$sep;
else
$schema_insert .= "".$sep;
}
$schema_insert = str_replace($sep."$", "", $schema_insert);
$schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
$schema_insert .= "\t";
print(trim($schema_insert));
print "\n";
}
?>
Try a query along these lines:
SELECT
t1.pro_id,
t2.pro_name,
t2.pro_desp,
t1.price,
t1.pro_model,
t4.cat_desp
FROM products t1
INNER JOIN pro_description t2
ON t1.pro_id = t2.pro_id
INNER JOIN pro_to_category t3
ON t1.pro_id = t3.pro_id
INNER JOIN category t4
ON t3.cat_id = t4.cat_id
I am trying to insert data posted from a form into my database using the following MySQL statement but it is producing my error 'Oooops! *** **** ***'
I know there is a connection because before I insert anything I test the users email address to see if it already exists and if it does it redirects the user to login. and this works so if the email doesn't exist in the database then it is suppose to be inserting the form data but it isn't.
* can someone please show me where I am going wrong? I have made sure I am spelling the table names correct and everything and am 100% sure I have posted all my form data correctly.
<?php
session_start();
include("config.php");
include("verify.php");
//retrieve our data from POST
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$email2 = $_POST['email2'];
$contactnum = $_POST['contactnum'];
$mobnum = $_POST['mobnum'];
$postcode = $_POST['postcode'];
$addres1 = $_POST['address1'];
$addres2 = $_POST['address2'];
$town = $_POST['town'];
$compname = $_POST['compname'];
$compreg = $_POST['compreg'];
$verify = $_POST['verify'];
$verification = $_POST['verification'];
$firstname = stripslashes($firstname);
$firstname = mysql_real_escape_string($firstname);
$lastname = stripslashes($lastname);
$lastname = mysql_real_escape_string($lastname);
$email = stripslashes($email);
$email = mysql_real_escape_string($email);
$email2 = stripslashes($email2);
$email2 = mysql_real_escape_string($email2);
$contactnum = stripslashes($contactnum);
$contactnum = mysql_real_escape_string($contactnum);
$mobnum = stripslashes($mobnum);
$mobnum = mysql_real_escape_string($mobnum);
$postcode = stripslashes($postcode);
$postcode = mysql_real_escape_string($postcode);
$addres1 = stripslashes($addres1);
$addres1 = mysql_real_escape_string($addres1);
$addres2 = stripslashes($addres2);
$addres2 = mysql_real_escape_string($addres2);
$town = stripslashes($town);
$town = mysql_real_escape_string($town);
$compname = stripslashes($compname);
$compname = mysql_real_escape_string($compname);
$compreg = stripslashes($compreg);
$compreg = mysql_real_escape_string($compreg);
$verify = stripslashes($verify);
$verify = mysql_real_escape_string($verify);
$verification = stripslashes($verification);
$verification = mysql_real_escape_string($verification);
$query = sprintf("SELECT * FROM supplier_registration WHERE supplier_email='%s'", mysql_real_escape_string($email2));
$result = mysql_query($query);
if(mysql_num_rows($result) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Found You!</h23><p>It appears that a user with that email address is already registered. Please Login below or click on our support section.</p> </div>';
header('Location: ../login.php');
} else {
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES (NULL, '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', NULL, NULL, NULL, '$compname', '$compreg', now())";
$result2 = mysql_query($sql);
if(mysql_num_rows($result2) > 0) {
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Thanks for Registering!</h23><p>You have successfully registered. We have sent you a verification email.</p> </div>';
header('Location: ../index.php');
}else{
$_SESSION['message2'] = '<div id="message_box3"><div class="boxclose" id="boxclose" onclick="this.parentNode.parentNode.removeChild(this.parentNode);"></div><h23>Oooops!</h23><p>It appears there was an error whilst attempting to register your details. Please try again later.</p> </div>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
} }
?>
The error may relate to the datatypes of the fields in your table.
In your code there is no conversion of strings to numbers.
If you add the table definition and the exact SQL error to your question more help can be given.
try this..
$sql = "INSERT INTO supplier_registration (id, first_name, last_name, supplier_email, contact_number, mobile_number, postcode, address1, address2, town, company_name, company_reg, date) VALUES ('', '$firstname','$lastname','$email2', '$contactnum', '$mobnum', '$postcode', '', '', '', '$compname', '$compreg', now())";
$result2 = mysql_query($sql);
It's because date in your query is a Reserved Keyword. so you'll have to put in [] like this [date]
I'm trying to build a script for a cron job that loads some values from a CSV file. This CSV file has 2 fields
product_id
price
The script will load the values from CSV, then it searches in mysql table for product_id matches. If found, it will update the price for that particular matched product_id in the table with the corresponding price in CSV.
I reached the below code so far but I got stuck at the part where I need to compare the array values from CSV with the array values from mysql.
<?php
// DB part
$con = mysqli_connect('localhost','user','pass','db');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"products");
$sql="SELECT product_id, price, FROM products";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
// CSV part
$file_handle = fopen("prices.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$code = str_replace(' ', '', $line_of_text[0]); //
$price = str_replace(' ', '', $line_of_text[1]); //
if (in_array($code, str_replace(' ', '', $row)))
{
echo "Match found";
print $code . " - " . $price . "<br />";
}
else
{
echo "Match not found";
print $code . " - " . $price . "<br />";
}
}
fclose($file_handle);
mysqli_close($con);
?>
You're storing just the first line of your products table in $row. Then you are doing some hard-to-understand comparisons, but all of those comparisons compare just your first row.
Here's what I'd do:
// Untested Code Below, Not Suited For Production Use
// ...
// open the DB connection, open the file, etc.
// ...
// iterate over the complete CSV file
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
$product_id = clean_product_id($line_of_text[0]);
$price = $line_of_text[1];
// for any entry in the CSV file check if there is more than one result
$sql="SELECT COUNT(*) FROM products WHERE product_id='$product_id'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
if( $row[0] == 1 ) {
// update the table price for the corresponding row (product), if there is just a single result for this $product_id
$sql="UPDATE products SET price = '$price' WHERE product_id='$product_id' LIMIT 1"; // in production code use mysqli_real_escape_string() on $price and $product_id!
$result = mysqli_query($con,$sql);
} else {
// if there are more results for this $product_id, add an error to your report.txt file
}
}
Can someone explain to me why this isn't working. Trying to convert to prepared statements as per the advice of everybody but get stuck right at the beginning...the connection is fine and it returns no message, but there is no entry into my table (called nametable)
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$con = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")");
}
$query = "INSERT INTO nametable (fname, lname) values (?,?)";
$stmt = mysqli_prepare($con, $query);
$firstName = "simon";
$lastName = "morris";
mysqli_stmt_bind_param($stmt,"ss",$firstname, $lastname);
mysqli_stmt_execute($stmt);
printf("Error: %s.\n", $stmt->error);
$stmt->close();
?>
I added the last 2 lines and the error that comes back is
Error: .
This works just fine but the prepared statements do not....anyone know why?
$sql="INSERT INTO nametable (fname, lname)
VALUES ('$firstName', '$lastName')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
try this
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "fidelio";
$dbname = "test";
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$firstName = "simon";
$lastName = "morris";
if ($stmtb = $mysqli->prepare("INSERT INTO nametable (fname, lname) values (?,?)")) {
$stmtb->bind_param('ss',$firstName, $lastName);
$stmtb->execute();
}else {printf("Prepared Statement Error: %s\n", $mysqli->error);}