I don't know how to title this...but anyway,
In my script if data doesn't exist, i insert a new row into a database and then check again for that row, for example:
1 search the db
2 if nothing
include(create.php) -> create entry
3 search the db for that row
Am I going to have to put in a usleep(1000000); between the include and the next search on the db? or is there something I am missing?
THanks!
Include the file create.php on top of your php script and call the functions you required inside this block
if ($number_of_rows < 1) { //call the functions from create.php you need here}
Seriously, why even have a create.php used in that manner anyway? Include create.php at the top of the page, put all the insert syntax into a function, and call it later on in your main script. That would work.
Or even better, don't even bother including it. Just run the queries straight in your main page. That way if you need to change something, you won't have to affect other pages.
You can use something like that
$query="Select * from table where id='23'";
$result=mysql_query($query);
if(mysql_num_rows($result)>0){
//result find in sql table
}else{
$query1="INSERT INTO table (schema) values(values)";
$result=mysql_query($query1);
}
sleep(1);
$query="select *...."
You can also use mysql INTERVAL query.It will automatic make a query after a particular interval and search for data.
Related
I have a database in phpMyAdmin that I have set up with XAMPP. I am working on a website that shows statistics from the user inputted scores in the database. Say that I would like to show the score percentile to the user after they submit their score: where do I write the query for that? In the HTML/PHP code? In phpMyAdmin? Somewhere else like a workbench or PopSQL?
I have successfully gotten the website to display the average score in any given table by writing this code to the HTML file:
<?php
$sql = "SELECT AVG(score) AS score FROM $input_subject";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_object($result) ;
echo nl2br("Average score for $input_subject: \n \n"
. round($row->score));
?>
It works, but when I search for tutorials for example for the percentile query or something like the CHECK function (to not accept anything less than 0 or more than 120) it seems that the queries are always written somewhere else than the HTML file.
Also, when I try to write the SQL code in phpMyAdmin, it always shows a bunch of error messages, even though I copy/pasted it in (changing the table names etc., of course).
So, do I need to look into some other programmes were to write the queries in or can I just write them into the HTML-file or in the phpMyAdmin? I'm a total newbie with this so anything helps!
Yes, you can write SQl queries(PHP) before your html code and also in between your html code, but make sure to change file extension to .php from .html otherwise PHP code will be printed on browser as it is.
"it seems that the queries are always written somewhere else than the HTML file."
we do this while using AJAX. we send data to server (a PHP file where we process data received) and server will give response. All this happens behind the scenes without page reloading.
in your case you can create a new PHP file lets say process.php, add your PHP code into it.
process.php
<?php
$sql = "SELECT AVG(score) AS score FROM $input_subject";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_object($result) ;
echo nl2br("Average score for $input_subject: \n \n"
. round($row->score));
?>
send user inputted scores from HTML file through ajax to PHP file (process.php) and response received from that file can be displayed in html file without page reloading.
you can go through the ajax api by following link jQuery-AJAX
i have a <?php include 'stats.php'; ?> on every page on my site. in the stats.php file there is a SQL Insert query that inserts data into a table in my database.
for some reason when visiting just one page it inserts 4 rows into the database - there is only one SQL Command.
why would it be doing this... below is ALL the code on the stats.php file
<?php
$activity_history_sql=
"INSERT into user_activity_history (user_seq, user, timestamp, ip_address, user_request_uri,
user_script_filename, user_script_uri, user_script_url, user_script_name, user_php_self)
values ('".$_SESSION["domain.co.uk"]["sequence"]."',
'".$_SESSION["domain.co.uk"]["forename"].' '.$_SESSION["domain.co.uk"]["surname"]."',
'".date("Y-m-d H:i:s")."',
'".$_SERVER["REMOTE_ADDR"]."',
'".$_SERVER["REQUEST_URI"]."',
'".$_SERVER["SCRIPT_FILENAME"]."',
'".$_SERVER["SCRIPT_URI"]."',
'".$_SERVER["SCRIPT_URL"]."',
'".$_SERVER["SCRIPT_NAME"]."',
'".$_SERVER["PHP_SELF"]."') ";
$activity_history_rs=mysql_query($activity_history_sql,$conn) or die(mysql_error());
?>
Please use require_once() when including stats.php.
The require_once statement is identical to require except PHP will
check if the file has already been included, and if so, not include
(require) it again.
Try different method for include like require_once('stat.php');
... that might solve your issue...
This script doesnt seem faulty.
ok - it seems to be working now. it may be that my cache hadn't refreshed properly. maybe it was still using the include rather than require_once
I have 2 php pages: query.php and result.php.
In query.php, I am executing a query (select) statement. It's returning a resultset
$rs = mysql_query($query);
Now I want to return this resultset from query.php to another page result.php and work with it. Like this:
In query.php:
return $rs
and in result.php:
$result = executeQuery($query) // we get the resultset in this variable
while ($row == mysql_fetch_array($result){
//do something
}
If the above is not recommended, please provide me with alternatives. But I want the query function and resultset in different pages.
You could just include results.php in your query.php page if you're just looking to keep the code separate in the source files but aren't actually required to redirect from one page to another:
In query.php:
$rs = mysql_query($query);
include "results.php";
In results.php:
while ($row == mysql_fetch_array($rs){
//do something
}
As far as trying to "return $rs" from one page to another that's not how PHP works. The return statement is only valid within a function. If you want to actually pass data from one PHP page to another and will be redirecting to that other page then you'll need to use either a session, a cookie, pass it in the URL (i.e. use GET) or use curl and add it as a POST var.
If this is really the way it must be, store the result set in a database somewhere or in a file and give each result a unique name. Then pass that name to the next page so it can be retrieved.
query.php will redirect to result.php?result_set=ab24sdfsdfklls for instance.
This has the added advantage that you can use the result_set as often as you want. Visitors can have multiple result sets during one visit. They can share the URL of the result set page with other people, etc.
Just be sure to eventually prune the data store as it will just keep on growing, but that's another matter entirely.
Is it possible to make a query using any of the methods of dsql() ?
something like:
$dq=$this->api->db->dsql()->execute('insert into table xx (field1,field2) values ('a','b')');
Thanks
DSQL is now refactored as a Separate Library: https://git.io/dsql
$this->api->db->dsql()->table('table')->set('field1','a')->set('field2','b')->do_insert();
Naturally you can also use
$this->api->db->dsql()->table('table')->set($associative_array)->do_insert();
Romans already showed an example of an insert. You can select an array of data like this (note the debug() is optional and will output the resulting sql statement at top of the page)
$db=$this->api->db->dsql()->table('table1 x')
->field('x.col1')
->field('sum(x.col2) col2')
// ->debug()
->join('table2 y','x.id=y.some_id')
->where('x.col3','Y')
->where('x.col4',$this->auth->api->get('id'))
->group('x.col2')
->order('x.col1')
->do_getAll();
and then loop through the result set to do something
foreach ($db as $row) {
if (is_array($row)) {
//do something here with row['col1'], row['col2']
}
}
just select a single value
$db=$this->api->db->dsql()->table('table1 x')
->field('x.col1')
->where('x.col2,'constant')
->do_getOne();
You can update records
$this->api->db->dsql()->table('table1 x')
->where('id',$somevariable)
->set('col1',$somevalue)
->debug()
->do_update();
and delete records
$this->api->db->dsql()->table('table1 x')
->where('id',$somevariable)
->do_delete();
Where possible, it's best to use models like below to persist your data but the nice thing about ATK4 is it doesnt get in the way so if you need to, you can execute SQL anywhere in your page to achieve a simple result.
$s=$p->add('Model_Story')->loadData($story);
$s->set('points', $value);
$s->update();
After years of false starts, I'm finally diving head first into learning to code PHP. After about 10 failed previous attempts to learn, it's getting exciting and finally going fairly well.
The project I'm using to learn with is for work. I'm trying to import 100+ fixed width text files into a MySql database.
So far so good
I'm getting comfortable with sql, and I'm learning some php tricks, but I'm not sure how to tie all the pieces together. The basic structure for what I want to do goes something like the following:
Name the text file I want to import
Do a LOAD DATA INFILE to import the data into one field it to a temporary db
Use substring() to separate the fixed width file into real columns
Remove lines I don't want (file identifiers, subtotals, etc....)
Add the files in the temp db, to the main db
Drop the temp db and start again
As you can see in the attached code, thigns are working fine. It gets the new file, imports it to the temp table, removes unwanted lines and then moves the content to final main database. Perfect.
Questions three
My two questions are:
Am I doing this 'properly'? When I want to run a pile of queries one after anohter, do I keep assinging mysql_query to random variables?
How would I go about automating the script to loop through every file there and import them? Rather than have to change the file name and run the script every time.
And, last, what PHP function would I use to 'select' the file(s) I want to import? You know, like attaching a file to an email -> Browse for file, upload it, and then run the script on it?
Sorry for this being an ultra-beginner question, but I'm having trouble seeing how all the pieces fit together. Specifcally I'm wondering how multiple sql queries get strung together to form a script? The way I've done it below? Some other way?
Thanks x 100 for any insights!
Terry
<?php
// 1. Create db connection
$connection = mysql_connect("localhost","root","root") or die("DB connection failed:" . mysql_error());
// 2. Select the database
$db_select = mysql_select_db("pd",$connection) or die("Couldn't select the database:" . mysql_error());
?>
<?php
// 3. Perform db query
// Drop table import if it already exists
$q="DROP table IF EXISTS import";
//4. Make new import table with just one field
if ($newtable = mysql_query("CREATE TABLE import (main VARCHAR(700));", $connection)) {
echo "Table import made successfully" . "<br>";
} else{
echo "Table import was not made" . "<br>";
}
//5. LOAD DATA INFILE
$load_data = mysql_query("LOAD DATA INFILE '/users/terrysutton/Desktop/importmeMay2010.txt' INTO table import;", $connection) or die("Load data failed" . mysql_error());
//6. Cleanup unwanted lines
if ($cleanup = mysql_query("DELETE FROM import WHERE main LIKE '%GRAND%' OR main LIKE '%Subt%' OR main LIKE '%Subt%' OR main LIKE '%USER%' OR main LIKE '%DATE%' OR main LIKE '%FOR:%' OR main LIKE '%LOCATION%' OR main LIKE '%---%' OR `main` = '' OR `main` = '';")){
echo "Table import successfully cleaned up";
} else{
echo "Table import was not successfully cleaned up" . "<br>";
}
// 7. Next, make a table called "temp" to store the data before it gets imported to denominators
$temptable = mysql_query("CREATE TABLE temp
SELECT
SUBSTR(main,1,10) AS 'Unit',
SUBSTR(main,12,18) AS 'Description',
SUBSTR(main,31,5) AS 'BD Days',
SUBSTR(main,39,4) AS 'ADM',
SUBSTR(main,45,4) AS 'DIS',
SUBSTR(main,51,4) AS 'EXP',
SUBSTR(main,56,5) AS 'PD',
SUBSTR(main,100,5) AS 'YTDADM',
SUBSTR(main,106,5) AS 'YTDDIS',
SUBSTR(main,113,4) AS 'YTDEXP',
SUBSTR(main,118,5) AS 'YTDPD'
FROM import;");
// 8. Add a column for the date
$datecolumn = mysql_query("ALTER TABLE temp ADD Date VARCHAR(20) AFTER Unit;");
$date = mysql_query("UPDATE temp SET Date='APR 2010';");
// 8. Move data from the temp table to its final home in the main database
// Append data in temp table to denominator table
$append = mysql_query("INSERT INTO denominators SELECT * FROM temp;");
// 9. Drop import and temp tables to start from scratch.
$droptables = mysql_query("DROP TABLE import, temp;");
// 10. Next, rename the text file to be imported and do the whole thing over again.
?>
<?php
// 5. Close connection
mysql_close($connection);
?>
If you have access to the command like, you can do all your data loading right from the mysql command line. Further, you can automate the process by writing a shell script. Just because you can do something in PHP doesn't mean you should.
For instance, you can just install PHPMyAdmin, create your tables on the fly, then use mysqldump to dump your database definitions to a file. like so
mysqldump -u myusername -pmypassword mydatabase > mydatabase.backup.sql
later, you can then just reload the whole database
mysql -u myusername -pmypassword < mydatabase.backup.sql
It's cool that you are learning to do things in PHP, but focus on doing the stuff you will do in PHP regularly rather than doing RDBMS stuff in PHP which is not where you should do it most of the time anyway. Build forms, and process the data. Learn how to build objects, and why you might want to do that. Head over and check out Symphony and Doctrine. Learn about the Front Controller pattern.
Also, look into PDO. It is very "bad form" to use the direct mysql_query() functions anymore.
Finally, PHP is great for templating and including disparate parts to form a cohesive whole. Practice making a left and top navigation html file. Figure out how you can include that one file on all your pages so that your same navigation shows up everywhere.
Then figure out how to look at variables like the page name and highlight the navigation tab you are on. Those are the things PHP is well suited for.
Why don't you load the files and process them in PHP, and use it to insert values in the actual table?
Ie:
$data = file_get_contents('somefile');
// process data here, say you dump it into a 2d array like
// $insert[$rows][$cols]
// then you can insert these into the db, ie:
$query = '';
foreach ($insert as $row) {
$query .= "INSERT INTO table VALUES ({$row[1]}, {$row[2]}, {$row[3]});";
}
mysql_query($query);
The purpose behind setting mysql_query to a variable is so that you can get the data you were querying for. In the case of any other query than SELECT, it only returns true or false.
So in the case where you are using if ($var = mysql...) you do not need the variable assingment there at all as the function returns true or false.
Also, I feel like doing all your substring and data file processing would be MUCH better suited in PHP. you can look into the fopen function and the related functions on the left side of that page.