Insert data from textfile to a database table - mysql

I would like to ask some help in inserting data from texfile to a database table....i created a php code to execute in inserting the files to the table but i have no luck in importing it...can anyone know to do this?help me please.
current php code:
<?php
$host= "localhost";
$user= "root";
$pass= "";
$db="klayton";
$connect= mysql_connect($host,$user,$pass);
if (!$connect)die ("Cannot connect!");
mysql_select_db($db, $connect);
$file = fopen("tblApplicants.txt","r");
while( $applicants = fgets($file) )
{
$sql = "INSERT INTO tb_applicants( aic,name ) VALUES ('$applicants')";
mysql_query($sql);
}
?>

Read each line from this file,skip every second line $i%2 == 0 do break;
explode it at " | " and get second ( $row[1] ) and nextone ( $row[2] ), then trim it, and make sql insert.
Try to do at this way

Related

"Undefined index" when trying to insert JSON file into SQL in PHP

im trying to insert multiple JSON files into a database(about 20-30 in total, im using 2 for now to test). All the files will have the same format. I inserted the files into an HTML table previously so i used the same loop so my script inserts any JSON file found in the directory into the database. I am however getting some errors 1) "Undefined index : Comments" and 2) Table 'serverd.serverd' doesn't exist. Any guidance would be appreciated. I have moved my brackets around but no luck.
'<?php
$connect =mysqli_connect("reservation","-----","-----","serverD") or
die("could not connect");
$dir = "/Users/-----/Desktop/reserve/sql";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
foreach(glob("*.json") as $filename) {
$jsondata = file_get_contents($filename);
$data = json_decode($jsondata, true);
$Manufacturer = $data['Comments']['Manufacturer'];
$Model = $data['Comments']['Model'];
$BIOSFamily = $data['Comments']['BIOSFamily'];
$BIOSDATE = $data['Comments']['BIOSDate'];
$SerialNumber = $data['Comments']['SerialNumber'];
$sql= " INSERT INTO serverD(Manufacturer, Model, BIOSFamily, BIOSDate, SerialNumber)
VALUES('$Manufacturer' , '$Model' , '$BIOSFamily' , '$BIOSDate' , '$SerialNumber')";
$query=mysqli_query($connect, $sql) or die (mysqli_error($connect));
}
}
}
?>'

Fetching data from database in php file

I am trying to fetch data from table. Table contains the data and query is true. Even why following query says $u and $t are not define. While condition becoming false.
I manually checked in database, it was showing results.
$url = "http://paulgraham.com/";
$user_id = "123";
$con = mysqli_connect('127.0.0.1', 'root', '', 'mysql');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return;
}
$result = mysqli_query($con,"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id."");
while ($row = #mysqli_fetch_array($result))
{
echo "hi";
$t = $row['title'];
$u = $row['url'];
}
echo "title is : $t";
echo "url is : $u";
Giving your SQL query :
"SELECT * FROM post_data WHERE userid =".$url." and url=".$user_id.""
You can see you are mixing url and userid... Change to :
"SELECT * FROM post_data WHERE userid =".$user_id." and url=".$url.""
Also define your $t and $u variables before your loop in case you have no record.
Next time, try to var_dump your generated query to test it.
If you were able to see the errors the DBMS is reporting back to PHP then you'd probably be able to work out what's wrong with the code.
Before the 'while' loop try...
print mysql_error();
(the obvious reason it's failing is that strings mut be quoted in SQL, and you've got the parameters the wrong way around)

Joomla 3.1 Database update query not working

Recently I was making an upload component for joomla 3.1 back-end.
based on How to Save Uploaded File's Name on Database
I was successful in moving the file to the hard-drive,
however I just cant get the update query to work based on the posted post above.
I don't get any SQL errors and saving works, but somehow ignores the database part.
I really hope I missed something obvious. (btw I don't know the joomla way of queries very well)
In phpmyadmin the following query works:
UPDATE hmdq7_mysites_projects
SET project_file = 'test'
WHERE id IN (3);
I have tried the following queries:
$id = JRequest::getVar('id');
$db =& JFactory::getDBO();
$sql = "UPDATE hmdq7_mysites_projects
SET project_file =' " . $filename. "'
WHERE id IN (".$id.");";
$db->setQuery($sql);
$db->query();
$colum = "project_file";
$id = JRequest::getVar('id');
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['project_file'] = strtolower( $file['name']['project_file'] );
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->update('#__mysites_projects');
$query->set($column.' = '.$db->quote($data));
$query->where('id'.'='.$db->quote($id));
$db->setQuery($query);
$db->query();
Here is the current code:
class MysitesControllerProject extends JControllerForm
{
function __construct() {
$this->view_list = 'projects';
parent::__construct();
}
function save(){
// ---------------------------- Uploading the file ---------------------
// Neccesary libraries and variables
jimport( 'joomla.filesystem.folder' );
jimport('joomla.filesystem.file');
$path= JPATH_SITE . DS . "images";
// Create the gonewsleter folder if not exists in images folder
if ( !JFolder::exists(JPATH_SITE . "/images" ) ) {
JFactory::getApplication()->enqueueMessage( $path , 'blue');
}
// Get the file data array from the request.
$file = JRequest::getVar( 'jform', null, 'files', 'array' );
// Make the file name safe.
$filename = JFile::makeSafe($file['name']['project_file']);
// Move the uploaded file into a permanent location.
if ( $filename != '' ) {
// Make sure that the full file path is safe.
$filepath = JPath::clean( JPATH_SITE . "/images/" . $filename );
// Move the uploaded file.
JFile::upload( $file['tmp_name']['project_file'], $filepath );
$colum = "project_file";
$id = JRequest::getVar('id');
$data = JRequest::getVar( 'jform', null, 'post', 'array' );
$data['project_file'] = strtolower( $file['name']['project_file'] );
$db =& JFactory::getDBO();
$query = $db->getQuery(true);
$query->update('#__mysites_projects');
$query->set($column.' = '.$db->quote($data));
$query->where('id'.'='.$db->quote($id));
$db->setQuery($query);
$db->query();
}
// ---------------------------- File Upload Ends ------------------------
JRequest::setVar('jform', $data );
return parent::save();
}
(Answered by the OP in comments. Converted to a community wiki answer. See Question with no answers, but issue solved in the comments (or extended in chat) )
The OP wrote:
Solved: after reviewing the post update record in database using jdatabase I made up some fixed test values. It turns out the query is correct but $data variable in the query had no data. $data['project_file'] = strtolower( $file['name']['project_file'] ); removed the array from first part and variable worked.

Sql to JSON/XML [duplicate]

I am trying to export my MySQL tables from my database to a JSON file, so I can list them in an array.
I can create files with this code no problem:
$sql=mysql_query("select * from food_breakfast");
while($row=mysql_fetch_assoc($sql))
{
$ID=$row['ID'];
$Consumption=$row['Consumption'];
$Subline=$row['Subline'];
$Price=$row['Price'];
$visible=$row['visible'];
$posts[] = array('ID'=> $ID, 'Consumption'=> $Consumption, 'Subline'=> $Subline, 'Price'=> $Price, 'visible'=> $visible);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
Now this reads a table and draws it's info from the fields inside it.
I would like to know if it is possible to make a JSON file with the names of the tables, so one level higher in the hierarchy.
I have part of the code:
$showtablequery = "
SHOW TABLES
FROM
[database]
LIKE
'%food_%'
";
$sql=mysql_query($showtablequery);
while($row=mysql_fetch_array($sql))
{
$tablename = $row[0];
$posts[] = array('tablename'=> $tablename);
}
$response['posts'] = $posts;
But now i am stuck in the last line where is says: $ID=$row['ID']; This relates to the info inside the Table and I do not know what to put here.
Also as you can see, I need to filter the Tables to only list the tables starting with food_ and drinks_
Any help is greatly appreciated:-)
There is no 'table id' in MySQL and therefore the result set from SHOW TABLES has no index id. The only index in the resultset is named 'Tables_in_DATABASENAME'.
Also you should use the mysqli library as the good old mysql library is depreacted. Having prepared an example:
<?php
$mysqli = new mysqli(
'yourserver',
'yourusername',
'yourpassword',
'yourdatabasename'
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") "
. $mysqli->connect_error;
}
$result = $mysqli->query('SHOW TABLES FROM `yourdatabasename` LIKE \'%food_%\'');
if(!$result) {
die('Database error: ' . $mysqli->error);
}
$posts = array();
// use fetch_array instead of fetch_assoc as the column
while($row = $result->fetch_array()) {
$tablename = $row[0];
$posts []= array (
'tablename' => $tablename
);
}
var_dump($posts);

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.