how do I source a .sql file, like the one below, through php?
CREATE DATABASE IF NOT EXISTS data_base;
USE data_base;
CREATE TABLE IF NOT EXISTS the_table(
package_name varchar(50) NOT NULL,
PRIMARY KEY (`package_name`)
)
I tried the following, but it doesn't work. I've tried to do some research and it seems I need to do something called LOAD DATA INFILE, but I don't understand it.
mysql_query("source C:/xampp/htdocs/Project1/mysql/source.sql;") or die(mysql_error());
How can I source an .sql file using PHP? Thanks.
You cannot just run an SQL script, even with mysqli::multi_query(). An SQL script can contain some commands that are recognized as builtin commands only by the mysql client, not by the MySQL server's SQL parser.
SOURCE is definitely a command that is preprocessed by the mysql client. The server does not understand that command. So you can't execute SOURCE on the server using the query API.
If you can restrict the content of your SQL script to exclude mysql client builtin commands, it might work to use mysqli::multi_query(). But it won't work for the full set of commands that are allowed in an SQL script.
See also my answer to Running MySQL *.sql files in PHP
LOAD DATA INFILE does not execute SQL statements to create tables, it just loads fields of a text file into an existing table.
You're mixing mysql command line statements with PHP functional calls. Do one or the other.
Utilize the mysql CLI (if available):
// executing mysql cli
exec("mysql < test.sql");
Or run the SQL with mysqli_multi_query():
// running the files contents in bulk
$sql= file_get_contents('test.sql');
mysqli_multi_query($sql);
Note: This is a potential security risk. Be advised.
Okay, this is a really old one I just stumbled across but I don't see anybody mention what I've always had work for me --NOTE I didn't look this up, just thought about it and it worked so I've used it for years, may not be the most secure way.
If the queries are already in a .sql file, I have always just read that in as a text file and passed it one line at a time with the fgets() function in php.
For example if this is in the .sql file.
CREATE DATABASE Testing123;
USE Testing123;
CREATE TABLE testData(name VARCHAR(32), age INT, town VARCHAR(32));
INSERT INTO testData(name, age, town) VALUES('Chris', 42, 'Clarksville');
Then uploading that from a webpage with this html form:
<form method="POST" action="import_sql_file.php" enctype="multipart/form-data">
<p><input type="file" name="data"/></p>
<p><input type="submit" value="Import"/></p>
</form>
The import_sql_file.php script I have always used to get it into the database looks like:
<?php
$file = $_FILES['data']['tmp_name'];
$db = new mysqli("localhost", "root", "");
$fromFile = fopen($file, "r");
while(!feof($fromFile)){
$query = fgets($fromFile);
$db->query($query);
}
$db->close();
?>
Using SOURCE $_FILES['data']['tmp_name'] failed on first thought I tried, then this thought worked on the second try so I never really looked into a more direct way to do it with SQL commands.
Related
Basically I want to communicate with a MYSQL server using php as the middle-ware.
I cannot connect directly to the database due to drivers needing to be installed and our IT will not allow drivers to be installed on our company computers.
I understand how to insert data using vba ->php->mysql but I cannot figure out how to get data from mysql to excel. vba->php->mysql->php->vba.
I want to do a query and send the results to vba excel.
Here is the VBA Code that works but it also sends multiple spaces back as well. Im not sure if this is the correct way to do this.
Private Sub ExtractPHP()
Dim item As String
Dim objHTTP As Object
Dim URL As String
Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://localhost/php/requestdata.php"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/x-www-form-urlencode"
objHTTP.send ("")
Worksheets("hiddendata").Range("k4").Value = Replace(objHTTP.responseText, " ", "")
End Sub
The PHP code is as follows.
<?php
$con = mysqli_connect("localhost","root","","php") or die("Connection was not created!");
$select = "select name FROM users where id=5";
$run = mysqli_query($con,$select);
$value = mysqli_fetch_array($run);
$result = $value["name"];
echo $result;
?>
Result that is placed in the excel file has multiple spaces below the text. Is this the correct way to communicate between excel and mysql?
I am not sure about the VBA method and what exactly you need to do but one solution would be to write requestdata.php to parse the result of your query into a .csv file and then load that into Excel via VBA. Parsing the result array into the .csv plain text format is made even more trivial by the fact that PHP already has a function fputcsv($file, $records) to use (documentation).
i can help you 10% cause i programming in several languages but nothing vba/excell .I programming in php too...anyway my answer for you is :
Let say you create in C: a new folder and you create a runme.bat file there.
Using one methods to run a external .bat file and to grab external result from that runme.bat more or less like in
Execute a command in command prompt using excel VBA
Wait for shell command to complete
you can use like me a method to run from that batch php cli:
you can drop runme.php in that folder as well:
<?php
if(isset($argv[1])){
echo($argv[1]);
//here you can drop some mysql
}
?>
then you should understand how to reconfiger php ini to connect to mysql ,some problems you can dare are
PHP: mysql_connect() won't work via command line
if you put a command like this one i already check via windows cmd and works
c:\xampp\php>php "c:\test\runme.php" yep2
and you are getting "yep2"
as c:\test\ 's runme.bat version :
rem #echo off
set parameter=%1
set PHP_BIN="c:\xampp\php\php.exe"
set script=%cd%\runme.php
%PHP_BIN% %script% %parameter%
and for test we call it in cmd : runme yep2
with the result: yep2
then with the batch modiffied you can fill data in mysql let's say you will call that not runme.php but putmysqldata.php .
at this point creating another file php to read from mysql (even you use only one file php to write or read by calling it by different parameter) so you will be able to read from mysql
so isn't easy if you don't know much vba or how to do it.
following these steps i think if you know some vba more than me you can figure out the shortest way.
I am using Birt 4.5 and PHP/MYSQL.
I am able to run birt reports with php. I have enabled tomcat and copied 'birt-runtime-4_5_0/WebViewerExample' to tomcat/webapps and renamed it to birt.
So I can run birt viewer with php;
<?php
$fname = "report/test.rptdesign&__showtitle=false";
$dest = "http://localhost:8081/birt/frameset?__report=";
$dest .= $fname;
header("Location: $dest" );
?>
Above code is working fine. But report connectstring already saved in test.rptdesign file.
I want to remove DB login credentials from test.rptdesign file and assign it while report open with PHP.
I have tried with report parameters. But all the parameters will display on browser address-bar.
Is there any secure way to do this? This is very important when we need to change the database location. It is very hard to change the data source of each and every .rptdesign file.
Thank You,
Supun
I don't believe using report parameters to handle a database connection is the right way. In addition to the address-bar problem you mentionned, it will cause unexpected issues: for example you won't be able to use this database to feed the dataset of another report parameter.
With Tomcat the best approach is to externalize the database connection in a connection pool: easy, robust, and reports might run significantly faster.
Alternatively the datasource can be externalized in a BIRT library (.rptlibrary) and shared across all report-designs: thus only the library needs to be updated when the database location is changing.
I agree with Dominique that sending the database parameters via the query is most likely an inappropriate solution - and you've not given any explanation of whether this is a requirement of the system.
But it is quite trivial to proxy the request via PHP and decorate the URL with the required parameters, something like...
<?php
$_GET['__showtitle']=$_GET['__showtitle'] ? $_GET['__showtitle'] : 'false';
$_GET['__report']=$fname; // NB this should be NULL in your code!
$_GET['dbuser']='a_db_user';
$_GET['passwd']='s3cr3t';
$qry=http_build_query($_GET);
$url="http://localhost:8081/birt/frameset?" . $qry;
// if its simply returning HTML, then just....
$fin=fopen($url, 'r');
while ($l=fgets($fin)) {
print $l;
}
exit;
If the returned content contains relative links the you'll need to rewrite the output stream. If the content type is unusual or you want to project other headers (e.g. for caching) to the browser, then you'll need to use Curl, capture the headers and relay them.
How to connect a html page to MySQL for example, i want to use <?php echo $_POST['username']; ?> in a HTML file. How do i connect to MySQL.
I have tryed this:
<?php
$con=mysql_connect("HOST", "USERNAME", "PASSWORD");
mysql_select_db("DATABASE");
?>
But it did not work.
HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.
You need to run it on a server not just in a browser.
Download Apache, Install PHP and save the file with a .php extension. It then should work.
Then you can echo out a $_POST value but you wont need SQL for that.
You cannot add whatever PHP code to an HTML page. it have to be a PHP page.
you don't need a mysql connection to echo $_POST['username']
you should never echo any $_POST variable. After processing a POST request, web-server ought to order the browser to reload the page using GET method. Not required for the AJAX calls though.
You cannot run PHP scripts in HTML files. Your file must have .php extension to run php scripts.
You should use MySQLi instead of mysql_ functions, because these functions are depricated!
You can not do this in html page, you need to write the code in a PHP file and save it on a server then execute it.
NOTE : mysql_* functions are deprecated, you should use the newer mysqli_* or PDO features of PHP.
Of course it should not work because html is client side and you are doing connection at server side so you might need a something great called server-side scripting language to accomplish your task.
How ever you can still do it in html page with ajax but as i said you has to use server-side scripting language.
I am using CodeCharge Studio to finish a large PHP application. This question isn't really CCS related, but a bit more general. I have a web form that is supposed to allow CRUD capabilities with a certain SQL Server table, but the Inserts keep failing without throwing any errors. What would be the best way to debug this?
When I'm having trouble with dynamically generated SQL queries, I typically echo out the query and try running that query on the console for the DB. Or alternatively, you could write a simple PHP function that writes out strings to a file, and that way you don't have to display the query directly on your page, but instead in a log file.
See what the actually query is and then try doing that query directly on the DB. Then you know whether it's a PHP issue or a DB issue.
Then go from there, depending on the outcome.
If the query looks OK, double check that the user running the query has insert rights to the database.
I've been caught out by that before.
You can monitor all sql queries in mysql as shown in this site, once you enable logging, run the query manually and see why its failing..this should be good starting point.
In addition to what's mentioned before, I can add my recent discovery:
trigger_error(print_r($your_var,1),E_USER_ERROR);
So you can output and debug your variable, even if it's a complex script with redirects, where simple echo would not help.
Dmitri.
You should try using FirePHP and log all the SQL to your Firebug:
An Example would be:
$sql = "SELECT * FROM table"
if (!mysql_query($sql)) {
// In un successfull log to FireBug
FB::error($data, "SQL error: ".mysql_error());
}
You can also implement the FB::error call from your own function, so you can later deactivate this behaviour modifying your function:
function log_error($data, $msg){
//dont forget to deactivate in case the application goes live!
FB::error($data, $msg);
}
if (!mysql_query($sql)) {
// In un successfull log to FireBug
log_error($data, "SQL error: ".mysql_error());
}
Most of the database connection classes in CodeCharge have a 'debug' flag which will automatically write all the page's database commands at the top of the page.
For example, in an old PHP project of mine, 'Common Files' the file 'db_mysql.php' (line 27):
public $Debug = 0; ## Set to 1 for debugging messages.
Change to '1' and publish that file. Load the web page. Change back and re-publish when done.
I've used this in CCS for PHP and ASP projects, and is likely in the other languages (not sure if or where to find in .NET projects).
I am getting the following error:
Access denied for user 'apache'#'localhost' (using password: NO)
When using the following code:
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
echo "<h1>Delete Story</h1>";
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)){
echo '<b>'.$row[1].'</b><span align="right">Delete</span>';
echo '<br /><i>'.$row[2].'</i>';
}
}
else {
echo "No stories available.";
}
?>
The connect.php file contains my MySQL connect calls that are working fine with my INSERT queries in another portion of the software. If I comment out the $result = mysql_query line, then it goes through to the else statement. So, it is that line or the content in the if.
I have been searching the net for any solutions, and most seem to be related to too many MySQL connections or that the user I am logging into MySQL as does not have permission. I have checked both. I can still perform my other queries elsewhere in the software, and I have verified that the account has the correct permissions.
And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
If it is saying 'apache#localhost' the username is not getting passed correctly to the MySQL connection. 'apache' is normally the user that runs the httpd process (at least on Redhat-based systems) and if no username is passed during the connection MySQL uses whomever is calling for the connection.
If you do the connection right in your script, not in a called file, do you get the same error?
Change the include() to require(). If the "connect.php" file can't be require()d, the script will fail with a fatal error, whereas include() only generates a warning. If the username you're passing to mysql_connect() isn't "apache", an incorrect path to the connect script is the most common way to get this type of error.
Don't forget to check your database error logs. You should be able to see if you are even hitting the DB. If you aren't, you should check your firewall rules on the box. On a linux box you can run iptables -L to get the firewall list rules.
Otherwise it will be a pure access issue. Do a "select * from mysql.user" to see if the apache user is even set up in there. Further, I would recommend creating an account specifically for your app as opposed to using apache, since any other app you create will run as apache by default, and could get unauthorized access to your db.
Just look up "GRANT" in the documentation # dev.mysql.com to get more info. If you have more specific questiosn regarding db, just edit your question, and i will take a look.
Does the connect.php script actually make the connection or does it just define a function you need to call to create a connection? The error you're getting is symptomatic of not having a previously established connection at all.
ETA: Also change the include to a require. I suspect it's not actually including the file at all. But include can fail silently.
Dude the answer is a big DUH! which unfortunately it took me a while to figure out as well. You probably have a function like dbconnect() and you are using variables from an include file to make the connection. $conn = mysql_connect($dbhost, $dbuser, $dbpass).
Well since this is inside a function the variables from the include file need to be passed to the function or else the function will not know what $dbhost, $dbuser and $dbpass is. A way to fix this is to make those variables global so your functions can pick them up. Another solution which is not very secure would be to write out you host, user and pass in the mysql_connect function.
Hope this helps but I had the same problem.
Did you remember to do:
flush privileges;
If the user is not set up then it will give the 'apache'#'localhost' error.
Just to check, if you use just this part you get an error?
<?php
include("../includes/connect.php");
$query = "SELECT * from story";
$result = mysql_query($query) or die(mysql_error());
If so, do you still get an error if you copy and paste one of those Inserts into this page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts use exactly the same syntax as this example.
Just to check, if you use just this part you get an error?
If so, do you still get an error if you copy and paste one of those Inserts into this >page, I am trying to see if it's local to the page or that actual line.
Also, can you post a copy of the connection calls (minus passwords), unless the inserts >use exactly the same syntax as this example.
Here is what is in the connection.php file. I linked to the file through an include in the same fashion as where I execute the INSERT queries elsewhere in the code.
$conn = mysql_connect("localhost", ******, ******) or die("Could not connect");
mysql_select_db("adbay_com_-_cms") or die("Could not select database");
I will try the working INSERT query in this area to check that out.
As to the others posting about the password access. I did, as stated in my first posting, check permissions. I used phpMyAdmin to verify that the permissions for the user account I was using were correct. And if it matters at all, apache#localhost is not the name of the user account that I use to get into the database. I don't have any user accounts with the name apache in them at all for that matter.
You can do one of the following:
Add the user "apache" and setup its privileges from phpmyadmin or using mysql on a shell
Tell php to run mysql_connect as another user, someone who already has the privileges needed (but maybe not root), look for mysql.default_user in your php.ini file.
Does the apache user require a password to connect to the database? If so, then the fact that it says "using password: NO" would lead me to believe that the code is trying to connect without a password.
If, however, the apache user doesn't require a password, a double-check of the permissions may be a good idea (which you mentioned you already checked). It may still be beneficial to try executing something like this at a mysql prompt:
GRANT ALL PRIVILEGES ON `*databasename*`.* to 'apache'#'localhost';
That syntax should be correct.
Other than that, I'm just as stumped as you are.
If indeed you are able to insert using the same connection calls, your problem most likely lies in the user "apache" not having SELECT permissions on the database. If you have phpMyAdmin installed you can look at the permissions for the user in the Privileges pane. phpMyAdmin also makes it very easy to modify the permissions.
If you only have access to the command line, you can check the permissions from the mysql database.
You'll probably need to do something like:
GRANT SELECT ON myDatabase.myTable TO 'apache'#'localhost';