Reading from a text file using PHP, adding to MySQL DB Problem - php

I have the following PHP code that allows me to read in from a text file line by line and write to a MySQL database. The text file consists of 13 values seperated by a space on each line. I have created the table separately in SQL, (with all the relevant Fields needed: Time, WIMU_ID, Ax, Ay etc) and then run the PHP below to INSERT the values into the table. My question is: Is there any way to create the table within the PHP code below and not have to CREATE the table in SQL first? Any help or suggestions appreciated.
Hugh.
<?php
$connection = mysql_connect('localhost','root','bonzo123');
mysql_query('create database gameDB');
mysql_select_db('gameDB');
$wx = array_map('trim',file("Thu-Apr-01-09_41_01-2010.txt_calibrated_120Hz.txt"));
$newwx = array();
foreach($wx as $i => $line)
{
if ($i > 1)
{
$tmp = array_filter(explode(' ',$line));
$q = "insert into test1 (Time, WIMU_ID, Ax, Ay, Az, Gx, Gy, Gz, Mx, My, Mz, Ax70, Ay37) values ('" . implode("','",$tmp) . "')";
$rw = mysql_query($q) or die("Problem with the query: $q<br>" . mysql_error());
}
}
?>

I think what you really want is this:
http://dev.mysql.com/doc/refman/5.1/en/load-data.html
which you can invoke through PHP but this would be a lot better unless you have specific reasons it cannot be used.

Sure, you can execute a command like:
CREATE TABLE IF NOT EXISTS `test1` (
...
);
To get your table creation query, issue this command after you've already created it in SQL:
SHOW CREATE TABLE `test1`;
Edit:
Note that you don't have to create the table in SQL directly, but since you already have, issuing the above command will give you exactly what you need to include in PHP to have it create the table on a future installation should the table not exist.
Note also that as #Jeremy suggests, you don't have to "roll your own" code to import a data file to a table. Once you've created the table, you can use LOAD DATA INFILE... to populate the table.
Edit 2:
Here is an example based on your comment:
<?php
// Connect to the database server
$connection = mysql_connect('localhost', 'root', 'bonzo123');
if (!$connection)
die('Could not connect: ' . mysql_error());
// Create database gameDB
if (mysql_query('create database gameDB', $connection)) {
echo "Database gameDB created successfully.\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n:";
}
// select which database to use
mysql_select_db('gameDB', $connection);
// create table test1 if it doesn't already exist
mysql_query('CREATE TABLE IF NOT EXISTS test1 (
v1 varchar(100),
v2 varchar(100),
v3 varchar(100),
v4 varchar(100),
v5 varchar(100),
v6 varchar(100),
v7 varchar(100),
v8 varchar(100),
v9 varchar(100),
v10 varchar(100)', $connection);
?>

Related

how to display information from a database in a web page without php

for my homework assignment, I need to display this information from my database in a table on a webpage. with all the research I've done, it seems that I need to use php. is there anyway to do this without php and just html? we haven't learned php yet so I'm confused. here is the database:
CREATE TABLE album (
id serial PRIMARY KEY,
name text,
number text,
year text,
artist text,
description text
);
CREATE TABLE label (
id serial PRIMARY KEY,
title text,
title_id integer REFERENCES album (id)
);
INSERT INTO album (name, number, year, artist, description) VALUES ('Reputation','15','2017','Taylor Swift','Reputation is Taylor Swifts sixth studio album');
INSERT INTO label (text, title_id) VALUES (Big Machine Records, 1);
INSERT INTO album (name, number, year, artist, description) VALUES ('Ripcord','13','2016','Keith Urban','Ripcord is Keith Urbans ninth studio album');
INSERT INTO label (text, title_id) VALUES (Capital Records Nashville, 2);
You can use Node, but I will recommend using php. It can be learned easily.
Remember those steps and it will be easy for you:
1)Php code is written inside tags and file must be saved with .php extension.
2)You need to connect to the database, there are multiple methods
https://www.w3schools.com/php/php_mysql_connect.asp
<?php
$servername = "localhost";
$username = "enterusername";
$password = "enterdatabasepassword";
$database="enterdatabasename";
// Create connection
$con = mysqli_connect($servername, $username, $password,$database);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
//this is a comment.
//Usually in localhost username is root and password is empty, so you must use
$username="root";
$password="";
3) Now you are connected to the database. This is how you get data from the database.
// $sql is just a variable
//$con is the variable that stores database connection. We declared it before.
$sql = mysqli_query($con, "SELECT * FROM album");
$count = mysqli_num_rows($sql); //mysqli_num_rows counts rows returned from database.
//now we check if database returned more than 0 rows
if($count>0){
//if returned rows >0 we fetch the data
while ($row = mysqli_fetch_array($sql)){
//Now we store each field in variables:
$id=$row['id'];
$name=$row['name'];
$number=$row['number'];
$year=$row['year'];
$artist=$row['artist'];
$description=$row['description'];
//Now we can create table
echo "<table><thead><tr> <td>id</td><td>name</td><td>number</td><td>year</td><td>artist</td><td>description</td></tr></thead>
<tbody>
<tr> <td>$id</td><td>$name</td><td>$number</td><td>$year</td><td>$artist</td><td>$description</td></tr>
</tbody>
</table>";
}
}
//Hope this helped you.
The process for read data from a database is: Presentation -> Language -> Driver -> Database.
Where:
Presentation-> The endpoint where you want show the data, it can be an app, webpage, console etc...
Language-> You need a programming language with an interface for the driver, generally this interface is a library.
Driver-> It's an abstraction layer that allow your library connect to a database.
Database-> your data here.
So you need to use programming to show data on a html page, but if you want only show the data you can use a viewer like this:
http://kripken.github.io/sql.js/GUI/

PHP multiple dropdown boxes with separated tables

okay as the title says I have a lot of tables and I need to display them in different drop down boxes. I have so far got the first table to display inside of a drop down box but I'm not really sure how too get the next table display.
<?php
$link = mysql_connect('server', 'user', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
$selected = mysql_select_db("database",$link)
or die("Could not select examples");
$sql="SELECT * FROM MOBO CPU, RAM,GPU, PSU, COMPUTERCASE";
$result = mysql_query($sql);
echo "<select name='mobo'>";
while ($row = mysql_fetch_array($result)) {
echo '<option value="'.$row["id"].'">'.$row["mobo"].'</option>';
}
echo "</select>";
?>
so this is my php so far and this is how the database looks.
CREATE TABLE MOBO (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,mobo VARCHAR(50) UNIQUE,quantity INT,price DECIMAL(18,2));
CREATE TABLE CPU (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, cpu VARCHAR(50) UNIQUE, quantity INT, price DECIMAL(18,2));
CREATE TABLE RAM (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,ram VARCHAR(50) UNIQUE,quantity INT,price DECIMAL(18,2));
and so on also I was hoping for somebody if they manager to fix my problem to explain in detail of how its done I'm a PHP Newb.
First of all, you're using mysql_* functions and they are removed in the latest version of PHP. While it works now, you will have an issue upgrading to a later version of PHP in the future. Use Mysqli or PDO (PDO is my preference)
Secondly, use lower case in identifiers such as your table names. This code might work on Windows, but if you ever migrate to Linux all of this will be case sensitive and this code will fail to work.
And what I do not understand in this code, while ($row = mysql_fetch_array($result)) {. mysql_fetch_array() returns the complete set of the result from the database. A while loop will constantly redefine it's value and you should instead use foreach($var = mysql_fetch_array(...) as $key => $value){} and then still it would be better to define $var in my example separately before using it in a foreach loop.
Then I think your issues are resolved.
$sql="SELECT * FROM mobo, cpu, ram, gpu, psu, case";
if($result = mysql_query($sql) != false){ // you should actually check if the query ran successfully.
$data = mysql_fetch_array($result);
//echo "<select name='mobo'>";
foreach($data as $row => $value){
echo $row, $value, "</br>";
}
//echo "</select>";
}
And last of all, selecting everything from multiple tables is a bad database setup. It will drag you down once you have a lot of results in the database and then it will be an issue to resolve this. Its perhaps better to use inner or outer joins by id.

OUTPUT clause get a return in PHP

After doing some research I think I need the Output clause. Essentially I am taking the below SQL and inserting into the specified table when I receive the location of a file I am uploading to the server. When I upload into the table the ID is an auto increment field and the primary key.
$conn = mysqli_connect($DBHOSTmy, $DBuser, $DBpass, $DBmy) or die("An error occurred connecting to the database " . mysqli_error($conn));
$query = "INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.id, Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq VALUES ('" . $source . "','" . $finalPdf . "','y',0,0);";
echo $query;
$result = $conn->query($query);
echo $result->num_rows;
$conn->close();
When this runs I get a return of INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq VALUES ('m','scan/WF_153_140812113520.pdf','y',0,0);, but I get no return of number rows.
I really just need the ID right this minute of the inserted row, but if we can get all of these fields that would be awesome.
I pretty much copied the usage of the OUTPUT clause from a few different places, but I don't see what I'm doing wrong to get no return...
I'm trying to do some research while writing this as I have not had good response rates because people think I'm lacking it so I also found: How do I use an INSERT statement's OUTPUT clause to get the identity value?... I changed my query only to:
$query = "DECLARE #OutputTbl TABLE (id INT, src VARCHAR, loc VARCHAR, iq INT, wq INT, pq INT);
INSERT INTO ebwf (src,loc,iq,wq,pq) OUTPUT Inserted.id, Inserted.src, Inserted.loc, Inserted.iq, Inserted.wq, Inserted.pq INTO #OutputTbl(id, src, loc, iq, wq, pq) VALUES ('" . $source . "','" . $finalPdf . "','y',0,0);";
I sadly still get nothing.. Hopefully this will give enough info as to what I should do next.
#cmorrissey provided a great solution...
$last_insert_id = $conn->insert_id;
This returns the last inserted id (I think primary key that is auto incremented is the most correct explanation.) This is better to use than OUTPUT. I'm not sure why OUTPUT is incorrect to use as I have seen it so many places and this only once from the user.

SQL Syntax Error when running through PHP but runs fine as an SQL Query

So, a snippet of my code which is resulting in an error is :
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName'); CREATE TABLE $tName(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
The output of this is :
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE test1(id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, D' at line 1
Well, the funny thing is that the exact code (except the variable - I just removed the $ sign) executed perfectly in phpMyAdmin.
Also, to prove that there is nothing really wrong with the php, the query executed without any error when it was only the INSERT query (and not the CREATE query).
mysqli_query can only perform one query at a time.
Try mysqli_multi_query instead.
As an aside creating tables on the fly is usually a sign of larger design issues. Schema should be relatively static while data should be dynamic.
You are trying to run two separate queries at a time in the code, which you can't run like that. You have to run them separately like below:
$con = mysqli_connect('localhost', 'root', '', 'notesDB');
if(isset($_POST['tableName'])) {
$tName = htmlentities($_POST['tableName']);
$firstQuery = mysqli_query($con,"INSERT into notes(Title) VALUES( '$tName')");
$secondQuery = mysqli_query("CREATE TABLE '$tName' (id int NOT NULL AUTO_INCREMENT, Title varchar(20) NOT NULL, Description varchar(100), PRIMARY KEY(id));");
if($firstQuery || $secondQuery){
header("Location: create2.php");
}
else
echo mysqli_error($con);
}
Your database architecture is wrong.
You shouldn't create tables on the fly. So, you have only register whatever new entity with simple regular INSERT query. And then use this entity's id to link records from another [already existing] table.
if(isset($_POST['tableName'])) {
$stm = mysqli_prepare($con,"INSERT into notes(Title) VALUES(?)");
$stm->bind_param("s",$_POST['tableName']);
$stm->execute();
}

How to copy a table from one mysql database to another mysql database

I need to copy a table from one database to another. This will be a cronjob. Which one is the best way to do it? PHP script or Shell Script. The problem with PHP, both databases has different usernames and passwords so I can't do it like this.
CREATE TABLE db1.table1 SELECT * FROM db2.table1
Should I just connect first DB get all records and insert all to new database using WHILE loop or there is a better way?
I prefer a shell script to do this instead of PHP script.
Thanks
If you need to copy the table on the same server you can use this code:
USE db2;
CREATE TABLE table2 LIKE db1.table1;
INSERT INTO table2
SELECT * FROM db1.table1;
It's copy+pasted from here:
codingforums.com
It's not my solution, but I find it useful.
I'd dump it. Much less complicated than anything PHP based.
mysqldump -u user1 -ppassword1 databasename > dump.sql
mysql -u user2 -ppassword2 databasename < dump.sql
MySQL reference: 4.5.4. mysqldump — A Database Backup Program
mysqldump -u user1 -ppassword1 databasename TblName | mysql -u user2 -ppassword2 anotherDatabase
It all can be done in a single command.
$L1 = mysql_connect('localhost', 'user1', 'pass1');
$DB1 = mysql_select_db('database1', $L1);
$L2 = mysql_connect('localhost', 'user2', 'pass2');
$DB2 = mysql_select_db('database2', $L2);
$re=mysql_query("SELECT * FROM table1",$L1);
while($i=mysql_fetch_assoc($re))
{
$u=array();
foreach($i as $k=>$v) if($k!=$keyfield) $u[]="$k='$v'";
mysql_query("INSERT INTO table2 (".implode(',',array_keys($i)).") VALUES ('".implode("','",$i)."') ON DUPLICATE KEY UPDATE ".implode(',',$u),$L2) or die(mysql_error());
}
user1, pass1, database1, table1 reffers to initial table
user2, pass2, database2, table2 reffers to copied table
$keyfield is the primary key of table
One liner with different servers
mysqldump -h host1 -u user1 -ppassword1 databasename TblName | mysql -h host2 -u user2 -ppassword2 anotherDatabase
Phpmyadmin has inbuilt functionality to copy tables from one database to another. Otherwise you can go with Pekka or export table then import table.
CREATE TABLE db_target.cloned_table
SELECT *
FROM db_source.source_table;
I'll put this answer up for anyone else looking for help.
If you don't have access to SSH then you can use PhpMyAdmin.
Simply:
browse to the table you want to move
Click the Operations tab
Use the MOVE or COPY to database function
If you come across privilege problems, you can temp grant a user Global permissions or add the same user to both databases.
exec('mysqldump --user=username --password="password" --host=hostname --database=database table1 table2 > databasedump.sql');
exec('mysql --user=username --password="password" --host=hostname --database=database < databasedump.sql');
insert into dest.table select * from orginal.table;
use <from database>
create table <to database.new name> as (select * from <table to copy>);
As it seems that nobody answered the initial question actually, here is my PHP script to backup a table from a remote MySQL server to a local MySQL server:
function backup_remote_table (
$remote_db_host, $remote_login, $remote_password, $remote_db_name, $remote_table_name,
$local_db_host, $local_login, $local_password, $local_db_name, $local_table_name
) {
// Generating names with time stamps for local database and/or local table, if not available
if ($local_table_name) {
$applied_local_table_name = $local_table_name;
} else {
$applied_local_table_name = $remote_table_name;
}
if ($local_db_name) {
$applied_local_db_name = $local_db_name;
if (!$local_table_name) {
$applied_local_table_name .= date_format(date_create(), '_Y_m_d_H_i_s');
}
} else {
$applied_local_db_name = $remote_db_name . date_format(date_create(), '_Y_m_d_H_i_s');
}
// Local server connection
$local_db_server = mysql_connect($local_db_host, $local_login, $local_password);
$local_db_server = mysql_query("CREATE DATABASE IF NOT EXISTS " . $applied_local_db_name, $local_db_server);
mysql_select_db($applied_local_db_name, $local_db_server);
// Remote server connection
$remote_db_server = mysql_connect($remote_db_host, $remote_login, $remote_password);
mysql_select_db($remote_db_name, $remote_db_server);
// Getting remote table data
$result_remote_table_info = mysql_query("SHOW CREATE TABLE " . $remote_table_name, $remote_db_server);
$remote_table_info = mysql_fetch_array($result_remote_table_info);
$remote_table_description = substr($remote_table_info[1], 13);
// Creating local table
$sql_new_table = "CREATE TABLE IF NOT EXISTS " . $applied_local_db_name . "." . $remote_table_description;
mysql_query($sql_new_table, $local_db_server);
// Getting all records of remote table
$result_remote_table_data = mysql_query("SELECT * FROM " . $table_name, $remote_db_server);
while ($remote_table_row = mysql_fetch_array($result_remote_table_data, MYSQL_ASSOC)){
// Browsing records of remote table
$sql_new_row = "INSERT INTO $applied_local_db_name.$applied_local_table_name (".implode(", ",array_keys($remote_table_row)).") VALUES (";
$extra_sql = "";
foreach (array_values($remote_table_row) as $value) {
if ($extra_sql != "") {
$extra_sql .= ",";
}
$extra_sql .= "'";
$extra_sql .= mysql_real_escape_string($value);
$extra_sql .= "'";
}
$sql_new_row .= $extra_sql . ")";
// Adding record to local table
$result_new_table_row = mysql_query($sql_new_row, $local_db_server);
}
mysql_free_result($result_remote_table_data);
return;
}
The solution above is not mine, I got it here, with minor changes.

Categories