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.
Related
I have two tables webadstats and webstatsclick and i want to make below query from these two tables.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(A.time))) as 'timestamp',
COUNT(B.click) as 'clickss'
FROM `webadstats` as A
LEFT JOIN `webstatsclick` as B
ON A.pubadhash = B.pubadhash
WHERE A.pubadhash='$pubadhash'
GROUP BY date(from_unixtime(A.time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$impressions[] = $row['impressions'];
$clicksall[] = $row['clickss'];
$timestamp[] = $row['timestamp'];
}
for($i=0; $i<count($clicksall); $i++){
$str .= $timestamp[$i] . '||' . $impressions[$i] . '||' . $clicksall[$i] ."\n";
}
}
echo $str;
But the problem is that this query is generating same values for both the variables impressions and clickss out of which value of impressions variable is correct.
1542434400||1270||1270
1542520800||1800||1800
1542607200||1745||1745
1542693600||1805||1805
1542780000||1615||1615
1542866400||1740||1740
1542952800||1740||1740
1543039200||1830||1830
1543125600||1830||1830
1543212000||1615||1615
1543298400||1880||1880
1543384800||2125||2125
1543471200||1530||1530
1543557600||1370||1370
1543644000||120||120
My both the DB structure is
webadstats db
webadstats db
webstatsclick db
webstatsclick db
Kindly help me where i am wrong.
Let's go back to the two query approach. The problem is, we've been trying to use JOIN on pubadhash but also WHERE with pubadhash, so the values get multiplied.
$sql2 = "SELECT
count(*) as 'impressions',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webadstats`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$sql3 = "SELECT
count(*) as 'clickss',
unix_timestamp(date(from_unixtime(time))) as 'timestamp'
FROM `webstatsclick`
WHERE pubadhash='$pubadhash'
GROUP BY date(from_unixtime(time))";
$result2 = mysqli_query($conn, $sql2);
if (mysqli_num_rows($result2)>0) {
while($row = mysqli_fetch_assoc($result2)) {
$arr[$row['timestamp']]['impressions'] = $row['impressions'];
$arr[$row['timestamp']]['timestamp'] = $row['timestamp'];
$arr[$row['timestamp']]['clickss'] = 0;
}
$result3 = mysqli_query($conn, $sql3);
if (mysqli_num_rows($result3)>0) {
while($row = mysqli_fetch_assoc($result3)) {
$arr[$row['timestamp']]['clickss'] = $row['clickss'];
}
}
foreach($arr as $clicks){
$str .= $clicks['timestamp'] . '||' . $clicks['impressions'] . '||' . $clicks['clickss'] ."\n";
}
}
echo $str;
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 have the following code on a .php page and I want to display it inside a table and only show the last 10 entries
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM dispenses";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Amount: " . $row["amount"] . " - Time Dispensed: ". $row["dispensed"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You could store all the results in an array and subsequently display only last 10 elements of that array.
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
for($i = count($results)-10; $i < count($results); $i++){
echo "<br> Amount: " . $results[$i]["amount"] . " - Time Dispensed: ". $results[$i]["dispensed"] . "<br>";
}
You can limit the number of results with LIMIT:
$sql = "SELECT * FROM dispenses LIMIT 10";
You can choose an offset as well. Check documentation for more.
p.s.: so in order to get last x entries using order by y use:
$sql = "SELECT * FROM (SELECT * FROM dispenses ".
"ORDER BY y DESC LIMIT 10) AS intermediate ORDER by y ASC";
Check this Fiddle to see how it works. I select the last three records based on id or insert date. I forgot to define an alias in the statement above. This is fixed now. Hope it helps ....
I have written following code for my sales_invoice.php
if(isset($_POST['submit1'])){
// $cat_array = $_POST['category_name'];
// $qua_array = $_POST['quantity'];
//$mrp_array = $_POST['mrp'];
//$vat_array = $_POST['vat'];
// print_r($_POST);
if(!empty($_POST['item_name']) && is_array($_POST['item_name'])){
$name_array =$_POST['item_name'];
//print_r($name_array);
for($j=0; $j< count($name_array);$j++){
$name = mysql_real_escape_string($name_array[$j]);
//echo $name;
//$n = explode('/',$name);
$sql = "select quantity from purchase_stock where item_name = '$name'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$num_rows = mysql_num_rows($res);
if($num_rows <=0){
echo "<b>not in stock</b>";
exit();
}
else
continue;
}
}
$sql = "insert into material_inv set order_date='$new_date', due_date='$new_date1', dealer='".$_POST['dealer']."', customer='".$_POST['customer']."'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
if($res == true){
echo "sales invoice created";
}
else
{
echo "error";
}
$myid = mysql_insert_id();
$sales_id = $myid;
//display_item();
// print_r($_POST);
if (!empty($_POST['category_name']) && !empty($_POST['item_name']) && !empty($_POST['quantity']) && !empty($_POST['mrp']) && !empty($_POST['vat']) &&
is_array($_POST['category_name']) && is_array($_POST['item_name']) && is_array($_POST['quantity']) && is_array($_POST['mrp']) && is_array($_POST['vat'])){
// echo 'start';
$name_array = $_POST['item_name'];
$cat_array = $_POST['category_name'];
$qua_array = $_POST['quantity'];
$mrp_array = $_POST['mrp'];
$vat_array = $_POST['vat'];
//print_r($mrp_array);
for ($i = 0; $i < count($name_array); $i++) {
$name = mysql_real_escape_string($name_array[$i]);
$cat = mysql_real_escape_string($cat_array[$i]);
$q = mysql_real_escape_string($qua_array[$i]);
$mrp = mysql_real_escape_string($mrp_array[$i]);
//echo $mrp;
$vat = mysql_real_escape_string($vat_array[$i]);
// mysql_query("INSERT INTO users (name, age) VALUES ('$name', '$age')");
$sql ="Insert into material_items SET category_name='$cat', item_name='$name', quantity='$q',
mrp='$mrp', vat='$vat', inv_id ='$sales_id'";
// echo $sql;
$res = mysql_query($sql) or die(mysql_error());
$sql1 = "Update stock set quantity=quantity -'$q' where item_name='$name'";
$res1 = mysql_query($sql1) or die(mysql_error());
echo "stock updated and invoice created";
}
}
}
I have first checked if item is present in purchase_stock table. (items are inserted in purchase_stock table after a purchase order is created). Then i insert in the sales table quantity which is sold. And then I write query to update stock table.
My question is do I write a insert query for stock table if no items are initially present there? Is it logically correct? Or should I keep same stock table to update quantity and items after purchase and sales transactions?
Here is an example of a stored procedure syntax
DELIMITER //
CREATE PROCEDURE GetProduct(IN param_ProductID INT)
BEGIN
SELECT *
FROM Products
WHERE ProductID = param_ProductID;
END //
DELIMITER ;
and this is how you call it from your php:
$mysqli->query("CALL GetProduct(".$param_ProductID.")");
regarding your question about inserting the the product,
you need to perform an UPSERT (insert if not exists and update if exists)
here is an example how to do it:
PHP / MySQL : Insert if doesnt exist else update
shimon :)
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
}
}