I've created a cron job to dump a table from a database and it works fine:
mysqldump -u username -ppassword dbname tablename > .../backups/matches.sql
This saved the file (note the ... is just the prefix of the location).
What I'd like to do is save this daily to a folder within backups. For example, backups/20150909/matches.sql
How can I achieve this with a variable?
Will the cron job create the folder if it does not exist?
Any help would be appreciated. There will be numerous tables that I want to backup daily, so I'd like to simply set up each cron job to do this.
I was able to resolve this by using PHP for my backup.
if(!file_exists($dir)) {
mkdir($dir);
}
if(!file_exists($dir)) {
echo "Directory (" . $dir . ") was not created.<br />";
} else {
echo "Directory (" . $dir . ") successfully created.<br />";
}
I then proceeded to get the tables
mysqli_select_db($conn, $dbname);
$search = "SHOW TABLES";
$result = mysqli_query($conn, $search);
while($row = mysqli_fetch_assoc($result))
{
$tables[] = $row['Tables_in_p3pro_p3live'];
}
Next was to write the sql files
foreach($tables as $key=>$value) {
$string = "mysqldump -u *username* -p*password* *dbname* " . $value . " > *path_to_dir*/backups/" . $foldername . "/" . $value . ".sql";
exec($string);
echo $value . " backup completed. <br />";
}
Related
I have already asked this related question: https://webmasters.stackexchange.com/questions/116055/using-mysql-database-data-directly-into-generating-articles-for-my-website-new/116056?noredirect=1#comment154341_116056
At this point, I'm starting to understand the code syntax and project structure a little better.
But I have made my database using MySQL console. it only has a few entries so far, I wanted to try to adapt the code in Zach's example, but here is the problem I have:
The problem is, I am unsure how to get the reference to my database object? In the code sample from Zach there is variable $db, I guess this is where i need to keep a reference to my own actual database.
Here is the psuedo-code (maybe) from Zach, note: he always said to me not to copy-paste it, but I'm just trying to see how I can use it in my project.
<?php
$SQL_Query = "SELECT * FROM your_table";
$SQL_Run = mysqli_query($db, $SQL_Query);
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
?>
So my question simply at moment is: How to create the reference $db?
Your answer is the correct way to establish a connection. I want to point out that there are two ways of writing that statement. The version you found online is one way, but from our previous conversation, you can write it like this:
<?php
// Establish how to log in
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// create the database connection
$db = new mysqli($servername, $username, $password, $dbname);
// if it fails, kill the site.
if (mysqli_connect_error($db)) {
die("Connection failed: " . mysqli_connect_error($db));
}
// your first query to grab all the article data
$SQL_Query = "SELECT * FROM your_table";
// run the query
$SQL_Run = mysqli_query($db, $SQL_Query);
// while data exists (it makes sure that you have post data, otherwise nothing shows up)
while ($row = mysqli_fetch_assoc($SQL_Run)) {
echo
"<section class='wrapper style1'>
<div class='inner'>
<header class='align-center'>
<h2>" . $row['imageurl'] . "</h2>
<img src='" . $row['title'] . "'>
<p>" . $row['description'] . "</p>
</header>
</div>
</section>";
}
// Close the connection
mysqli_close($db);
?>
You will notice that the connections are written like a function.
mysqli_num_rows($result);
instead of
$result->num_rows
Both do the same thing, just a personal preference. That should hopefully clear some things up from your first post :)
I have got further on and I think have answered my own question. I found it a bit tricky to research because I don't understand all the different terms and names of features/api/scripts/etc. But I had just to read the documentation for mysqli_connect(), I set up the code as follows and now I have pulled all the data from the database into words on my html/php files.
From here I think I can rewrite the code to first sort it by date and then can of course put the latest posts at the top of each page etc.
I can also allow the user to click 'Genre' and only view Comedy for example.
Here is the code just to get the data parsed into my index.php file:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "yourpasswordhere";
$dbname = "yourdatabasenamehere";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, type, title FROM releases";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Type: " . $row["type"]. " - Title " . $row["title"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
I extended upon the above work by making the php script fetch all the entries in the database and create the previous html article I had once for each entry. In the SELECT statement I can control which types of entries are displayed (eg. For a certain category). Here was how I did it:
// make an html article based snippet (image, title, description, etc),
//once for each entry in the database table...
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "somepassword";
$dbname = "somedatabasename";
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// check connection
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM releases ORDER BY id DESC";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
echo '<section class="wrapper style1">';
echo '<div class="inner">';
echo '<header class="align-center">';
echo '<h2>'. $row["title"] . '</h2>';
echo '<div class="image fit">';
echo '<img src='. $row["imgurl"] .'>';
echo '</div> <p> RELEASE TITLE: ' . $row["title"] . '<br /> DATE POSTED: ' . $row["postdate"] . '<br /> DESCRIPTION: ' . $row["description"] . '</p>';
echo 'DOWNLOAD LINK: '.$row["link"].' <br />';
$NfoLink = $row["nfolink"];
if ($NfoLink != 'not found' && $NfoLink != '')
{
echo 'NFO LINK/MORE DOWNLOADS: '.$row["nfolink"].'';
}
echo '</header>';
echo '</div>';
echo '</section>';
}
}
else
{
echo "0 results";
}
$conn->close();
?>
I need to create a div that only shows the information of the database, how should i connect the div to mysql so it only shows my database information?
I'm not sure I'm understanding your question... but I'll give it a try. The code below this will select whatever you tell it to from the database and echo it into a table.
<?php
$db = mysqli_connect('host', 'username', 'password', 'database');
$sql = "SELECT * FROM database"
mysqli_stmt_bind_param($db, "params here", your info here);
$res = mysqli_stmt_execute($sql);
mysqli_stmt_close($sql);
mysqli_close($db);
echo "<table>";
while($row = mysqli_fetch_array($res)){ //Creates a loop to loop through results
echo "<tr><td>" . $row[''] . "</td><td>" . $row[''] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
?>
I keep getting this error when i try and run some mysql code from a php file on my server :
Table 'leaderboard.u' doesn't exist
The thing is that the table leaderboard does exist . Its been setup the same way that I have it setup in xampp . It also works on xampp and worked on the server until recently .
What could be causing this ?
EDIT :
<?php
include("../../config/connect.php");
if(!empty($_GET['id']) && !empty($_GET['data']))
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
$result = mysqli_query($connection,"update userbadges set $key='$data' where id='$id'");
if(!$result) {
echo mysqli_error($connection);
exit;
}
echo 'database update ' . mysqli_affected_rows($connection) . ' rows';
}
?>
I host at hostgator and have about 30 mysql databases (all different websites that sit on the same server). For the last year.. no problems and suddenly, the last 2 days, I've seen 5 - 10 of these databases marked as 'crashed' and they return no results... so my websites display no info. I have to run a "repair table mytable" to fix these and then they work great again.
Instead of logging in to go through the databases 1 by 1 every morning, is there a way I could setup a php page to connect to all 30 databases and run a simple select statement.. and if it works, return
"database db1 is working"
"database db2 is working"
and then when not working, return
"no reply from db3"
....or something similar?
Thanks!
There's no reason you couldn't have a script that lists all of your databasenames and login credentials, and try to connect in turn to each:
$logins = array(
array('dbname' => 'blah', 'user' => 'username1', 'password' => 'password1'),
array('dbname' => 'yuck', ....)
...
);
$failures = array();
foreach ($logins as $login) {
$con = mysql_connect('servername', $login['user'], $login['password']);
if (!$con) {
$failures[] = $login['dbname'] . " failed with " . mysql_error();
continue;
}
$result = mysql_select_db($login['dbname']);
if (!$result) {
$failures[] = "Failed to select " . $login['dbname'] . ": " . mysql_error();
continue;
}
$result = mysql_query("SELECT something FROM sometable");
if (!$result) {
$failures[] = "Faile to select from " . $login['dbname'] . ": " . mysql_error();
continue;
}
if (mysql_num_rows($result) != $some_expected_value) {
$failures[] = "Got incorrect rowcount " . mysql_num_rows($result) . " on " . $login['dbname'];
}
etc....
mysql_close();
}
if (count($failures) > 0) {
echo "Failures found: "
print_r($failures);
}
You should be able to do something like the following:
<?php
//connect to database
mysql_connect('database','user','password');
//get all database names
$result = mysql_query("show databases;");
//iterate over all databases returned from 'show databases' query
while($row = mysql_fetch_array($result)) {
//DB name is returned in the result set's first element. select that DB
mysql_selectdb($row[0]);
//get all tables in the database
$query = "show tables;";
$result2 = mysql_query($query);
echo "Query: (".$row[0].")$query\n";
echo mysql_error();
//iterate over all tables in the current database
while($row2 = mysql_fetch_array($result2)) {
//the first element of the returned array will always be the table name, so:
$query = "select * from ".$row2[0]." where 1=1;";
$result3 = mysql_query($query);
echo "Query:\t(".$row[0].'/'.$row2[0].")$query\n";
//If mysql_query returns false (i.e., $result3 is false), that means that
// the table is damaged
if(!$result3) {
echo "***Error on table '".$row2[0]."' *** ... Fixing...";
//So, we repair the table
mysql_query("repair table ".$row2[0].";");
}
}
}
?>
I want to pass parameters to a batch file which will then inserted into mysql database.
lunch.bat name surname
echo off
mysql -uusername -ppassword -e "set #1:=name; set #2:=surname; source insert.sql;"
In insert.sql
insert into mytable(namecol,surnamecol) values(#1,#2);
Someone can help me in writing both scripts?
Thanks
Added single quotes to handle string input... still wobly if quotes are supplied in the paramaters
#echo off
mysql -uusername -ppassword -e "set #1:='%1'; set #2:='%2'; source insert.sql;"
Done!
Here is a piece of my code that I been working on, although it post to database every time you visit the page. I've tried to add "unique key" with rand() in database. But the code still grabs "rand() on page" and post without "Submit" from form. Anyways this is how I insert data to Mysql. My database creates time and day timestamp() & order by "id."
// Select from database working
$statement = $database->prepare('SELECT * FROM pressroom ORDER BY id
DESC
LIMIT 0 , 30' );
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<td><br>";
echo "<center><b>" . $R[ $x ]['name'] . "</th>";
echo ": <left></b>" . $R[ $x ]['comment'] . "</th>";
echo "<center>" . $R[ $x ]['date'] . "<hr></td>";
echo "</tr>";
}
}
// Make sure that the 'values' are in the same order or as
your table
$query = "INSERT INTO pressroom(first_name, last_name, Password )
VALUES ('table1','table2','table3')";
//connection prepare
try {
$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $database->query($query);
//Prints results that are added to table
print_r($results);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}