Insert into mysql - mysql

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();
}

Related

Cron Job mysqldump to daily folder

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 />";
}

Saving Each Token in Separate row in Database

I am trying to save each string token in separate row in database, so that i can compare it with other string Tokens.
I am using PHP explode function and my syntax is:
<?php
$someWords = "Please don't, blow me to pieces.";
$wordChunks = explode(" ", $someWords);
for($i = 0; $i < count($wordChunks); $i++){
echo "Piece $i = $wordChunks[$i] <br />";
$con = mysqli_connect("localhost","","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO TableName (file1) VALUES ('$wordChunks')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully";
mysqli_close($con);
}
?>
It gives this output
And i want this output
[
Use the MySQL mysqli_real_escape_string function to escape the string before including it in the query:
$sql = 'INSERT INTO TableName (file1) VALUES ('.mysqli_real_escape_string($wordChunks[$i]).')';

Displaying MYSQL data in a HTML table AFTER a search

I want to thank everyone here for the help I have recieved so far. My next question is a bit more complicated.
So I have a database set up on my server, and I have a form on my website where I am submitting data to my MYSQL database.
After I submit the data, I am having trouble searching for it, displaying possible results, and then making those results HYPERLINKED so that the user can find out more about they are looking for.
My "common.php" script is set up like this:
<?php
$username = "XXX";
$password = "XXX";
$hostname = "XXX"; 
$database = "XXX";
mysql_connect($hostname, $username, $password, $database) or die
("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
?>��
My "insertdata.php" script is set up like this:
<?php
require("common.php");
// connect with form
$name=$_POST['firstname'];
$lastname=$_POST['lastname'];
$city=$_POST['city'];
$state=$_POST['state'];
$zip=$_POST['zip'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$various=$_POST['various'];
$other=$_POST['other'];
// insert data into mysql
$query="INSERT INTO datatable
(
firstname,
lastname,
city,
state,
zip,
phone,
email,
various,
other,
)
VALUES
(
'$firstname',
'$lastname',
'$city',
'$state',
'$zip',
'$phone',
'$email',
'$various',
'$other',
)";
$result=mysql_query($query);
// if successfull displays message "Data was successfully inserted into the database".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='insert.php'>Back to main page</a>";
}
else {
echo "ERROR... data was not successfully insert into the database";
}
mysql_close();
?>��
From there, I want to make the inserted data searchable.
My problem is, when the search is completed, I want to only display the First Name and Last Name in two separate columns.
From there, I want a link displayed in a third separate column with a link in each row that says "View Record Details."
Finally, when "View Record Details" in clicked, it brings me to the correct record, formatted again in an HTML table.
The closest I have come to a solution is:
<?php
require("common.php");
$query="SELECT * FROM datatable";
$result=mysql_query($query);
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
$firstname=mysql_result($result,$i,"firstame");
$lastname=mysql_result($result,$i,"lastname");
$i++;}
?>
As an additional question, when I use PDO, does that change my HTML?
Switch to PDO. Your code will look something like this:
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$sql = 'SELECT * FROM datatable';
foreach ($conn->query($sql) as $row) {
print $row['firstname'] . "\t";
print $row['lastname'] . "\n";
}
EDIT:
To link back for details add this line after the 2nd print:
print "<a href='somephp.php?idx=" . $row[ 'idx' ] . "'>link here</a>";
You'll need another php file called 'somephp.php':
$conn = new PDO('mysql:host=db_host;dbname=test', $user, $pass);
$idx = $_REQUEST[ 'idx' ];
$sql = 'SELECT * FROM datatable where idx = ?';
$stmt = $conn->prepare( $sql );
$stmt->bindParam( 1, $idx );
$stmt->execute();
$row = $stmt->fetch();
// now print all the values...
print $row['firstname'] . "\t";
print $row['lastname'] . "\t";
print $row['address'] . "\t";
and so on...
NOTE: This depends on each record having a unique key 'idx'. I don't see this in your values above so you'll have to find a way to incorporate it if you want to use this code.
ALSO: You ask - does this change the HTML and does this handle table formatting - No to both. You do all the HTML formatting via the print statements. All PHP does it output lines to the browser.

Can I construct a php page to run a query check against 30 mysql databases?

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].";");
}
}
}
?>

Search for all occurrences of a string in a mysql database [duplicate]

This question already has answers here:
Search text in fields in every table of a MySQL database
(27 answers)
Closed 6 years ago.
I'm trying to figure out how to locate all occurrences of a url in a database. I want to search all tables and all fields. But I have no idea where to start or if it's even possible.
A simple solution would be doing something like this:
mysqldump -u myuser --no-create-info --extended-insert=FALSE databasename | grep -i "<search string>"
In phpMyAdmin a 'Search' feature is available:
Select particular database not table.
Click 'Search' tab
Enter the search term you want
Select the tables you want to search in
phpMyAdmin screen shot:
The 'Search' feature is also available in MySQL Workbench:
Database Menu > Search Table Data
Select database and tables you want to search (it will search in selected tables only)
In search you can use wildChars.
MySQL Workbench screen shot:
Old post I know, but for others that find this via Google like I did, if you have phpmyadmin installed, it has a global search feature.
Using the MySQL Workbench, you can search for a string from the "Database" -> "Search Table Data" menu option.
Specify LIKE %URL_TO_SEARCH% and on the left side select all the tables you want to search through. You can use "Cntrl + A" to select the whole tree on the left, and then deselect the objects you don't care about.
You can do this by using HeidiSQL without generating Db dumps
Steps:
1) Select the database you need to search in from the left panel of GUI.
2) Export > Export Database as SQL
3) In Table Tools window select "FIND TEXT" tab.
4) Provide your string to search and click "FIND".
5) It will list all the tables contains our string.
6) Select the row with higher relevance %.
7) Click "SEE RESULTS"
I was looking for this myself when we changed domain on our Wordpress website. It can't be done without some programming so this is what I did.
<?php
header("Content-Type: text/plain");
$host = "localhost";
$username = "root";
$password = "";
$database = "mydatabase";
$string_to_replace = 'old.example.com';
$new_string = 'new.example.com';
// Connect to database server
mysql_connect($host, $username, $password);
// Select database
mysql_select_db($database);
// List all tables in database
$sql = "SHOW TABLES FROM ".$database;
$tables_result = mysql_query($sql);
if (!$tables_result) {
echo "Database error, could not list tables\nMySQL error: " . mysql_error();
exit;
}
echo "In these fields '$string_to_replace' have been replaced with '$new_string'\n\n";
while ($table = mysql_fetch_row($tables_result)) {
echo "Table: {$table[0]}\n";
$fields_result = mysql_query("SHOW COLUMNS FROM ".$table[0]);
if (!$fields_result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
if (mysql_num_rows($fields_result) > 0) {
while ($field = mysql_fetch_assoc($fields_result)) {
if (stripos($field['Type'], "VARCHAR") !== false || stripos($field['Type'], "TEXT") !== false) {
echo " ".$field['Field']."\n";
$sql = "UPDATE ".$table[0]." SET ".$field['Field']." = replace(".$field['Field'].", '$string_to_replace', '$new_string')";
mysql_query($sql);
}
}
echo "\n";
}
}
mysql_free_result($tables_result);
?>
Hope it helps anyone who's stumbling into this problem in the future :)
Found a way with two (2) easy codes here. First do a mysqldump:
mysqldump -uUSERNAME -p DATABASE_NAME > database-dump.sql
then grep the sqldump file:
grep -i "Search string" database-dump.sql
It possible also to find/replace and re-import back to the database.
SQLyog is GUI based solution to the problem of data search across all columns, tables and databases. One can customize search restricting it to field, table and databases.
In its Data Search feature one can search for strings just like one uses Google.
MikeW presented an interesting solution, but as mentioned in comments, it's a SQL Server solution not a MySQL solution. Here is a MySQL solution:
use information_schema;
set #q = 'Boston';
set #t = 'my_db';
select CONCAT('use \'',#q,'\';') as q UNION
select CONCAT('select \'', tbl.`TABLE_NAME`,'\' as TableName, \'', col.`COLUMN_NAME`,'\' as Col, `',col.`COLUMN_NAME`,'` as value from `' , tbl.`TABLE_NAME`,'` where `' ,
col.`COLUMN_NAME` , '` like \'%' ,#q, '%\' UNION') AS q
from `tables` tbl
inner join `columns` col on tbl.`TABLE_NAME` = col.`TABLE_NAME`and col.DATA_TYPE='varchar'
where tbl.TABLE_SCHEMA = #t ;
I can't remember where I came across this script, but I've been using it with XCloner to move my WP multisites.
<?php
// Setup the associative array for replacing the old string with new string
$replace_array = array( 'FIND' => 'REPLACE', 'FIND' => 'REPLACE');
$mysql_link = mysql_connect( 'localhost', 'USERNAME', 'PASSWORD' );
if( ! $mysql_link) {
die( 'Could not connect: ' . mysql_error() );
}
$mysql_db = mysql_select_db( 'DATABASE', $mysql_link );
if(! $mysql_db ) {
die( 'Can\'t select database: ' . mysql_error() );
}
// Traverse all tables
$tables_query = 'SHOW TABLES';
$tables_result = mysql_query( $tables_query );
while( $tables_rows = mysql_fetch_row( $tables_result ) ) {
foreach( $tables_rows as $table ) {
// Traverse all columns
$columns_query = 'SHOW COLUMNS FROM ' . $table;
$columns_result = mysql_query( $columns_query );
while( $columns_row = mysql_fetch_assoc( $columns_result ) ) {
$column = $columns_row['Field'];
$type = $columns_row['Type'];
// Process only text-based columns
if( strpos( $type, 'char' ) !== false || strpos( $type, 'text' ) !== false ) {
// Process all replacements for the specific column
foreach( $replace_array as $old_string => $new_string ) {
$replace_query = 'UPDATE ' . $table .
' SET ' . $column . ' = REPLACE(' . $column .
', \'' . $old_string . '\', \'' . $new_string . '\')';
mysql_query( $replace_query );
}
}
}
}
}
mysql_free_result( $columns_result );
mysql_free_result( $tables_result );
mysql_close( $mysql_link );
echo 'Done!';
?>
If you can use a bash - here is a script:
It needs a user dbread with pass dbread on the database.
#!/bin/bash
IFS='
'
DBUSER=dbread
DBPASS=dbread
echo -n "Which database do you want to search in (press 0 to see all databases): "
read DB
echo -n "Which string do you want to search: "
read SEARCHSTRING
for i in `mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "show tables" | head -1\``
do
for k in `mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | grep -v \`mysql $DB -u$DBUSER -p$DBPASS -e "desc $i" | head -1\` | grep -v int | awk '{print $1}'`
do
if [ `mysql $DB -u$DBUSER -p$DBPASS -e "Select * from $i where $k='$SEARCHSTRING'" | wc -l` -gt 1 ]
then
echo " Your searchstring was found in table $i, column $k"
fi
done
done
If anyone wants an explanation: http://infofreund.de/?p=1670
Scott gives a good example of how to do it, but the question is why would you want to? If you need to do a find-and-replace on a specific string, you could also try doing a mysqldump of your database, do a find-and-replace in an editor, then re-load the database.
Maybe if you gave some background on what you are trying to achieve, others might be able to provide better answers.
I was looking for the same but couldn't find it, so I make a small script in PHP, you can find it at:
http://tequilaphp.wordpress.com/2010/07/05/searching-strings-in-a-database-and-files/
Good luck!
(I remove some private code, let me know if I didn't break it in the process :D)
The first 30 seconds of this video shows how to use the global search feature of Phpmyadmin
and it works. it will search every table for a string.
http://www.vodahost.com/vodatalk/phpmyadmin-setup/62422-search-database-phpmyadmin.html
In unix machines, if the database is not too big:
mysqldump -u <username> -p <password> <database_name> --extended=FALSE | grep <String to search> | less -S
Not an elegant solution, but you could achieve it with a nested looping structure
// select tables from database and store in an array
// loop through the array
foreach table in database
{
// select columns in the table and store in an array
// loop through the array
foreach column in table
{
// select * from table where column = url
}
}
You could probably speed this up by checking which columns contain strings while building your column array, and also by combining all the columns per table in one giant, comma-separated WHERE clause.