Inserting multiple rows into database - php

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

Related

Can I write all my SQL queries to phpMyAdmin / HTML-file or do I need to use other programmes?

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

setting enum value to 1 on link click?

can someone please help, i am trying to get the column 'privellages' (i know its spelt wrong) to update in my table 'ptb_permissions' when a link is clicked.
basically i've done this before for loads of other things and its worked fine its just this not working for some reason.
users are notified in their inbox when a user sends a request to view their pictures. and the user will have two links one to approve or one to delete the request.
if they click approve then this should update the enum colum 'privellages' from 0 to 1.
this is not working. im not getting any errors im just not getting anything happening. please can someone show me where im going wrong thanks.
Yes this is ok
contents of approve_priv_pix.php;
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
approve_pix ($_GET['picture'], $_SESSION['user_id']);
header("Location: {$_SERVER['HTTP_REFERER']}");
?>
mysql function:
function approve_pix($picture, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
mysql_query($query, $connection);
}
$_GET['picture'] should be $_GET['pix']
Also double check your privellages column enum values.
Yes this is ok
Here you have pix as a key, but in approve_priv_pix.php you are taking picture id from $_GET['picture']. Suppose it should be replaced with $_GET['pix']
Also, not sure why do you have <?php echo $pix['user_id']; ?> in link code. Possibly it should be something like <?php echo $pix['picture_id']; ?>
Additionally, you code is opened to sql injections. Here:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=$picture
AND to_user_id=$user";
Instead of that you should better do:
$query = "UPDATE ptb_permissions
SET privellages='1'
WHERE id=" .mysql_real_escape_string($picture) . "
AND to_user_id=" .mysql_real_escape_string($user);
More details about mysql_real_escape_string. Take a look at warning message on top of that page. mysql extension is deprecated and will be remove soon. For new projects you should better use PDO or MySQLi extensions.
Another note: global $_SESSION; is not needed at all. It is accessible form any place in PHP by default.
im not getting any errors im just not getting anything happening
To see all errors you should set error_reporting to E_ALL (in your ini file or directly in code). With this option enabled you would see all notices/warnings/errors.

php mysql query in function not working

I have a mysql query that returns sum of values in multiple columns. The query is right and everything is working normally when i include it in the main page. But the problem starts when i make a function in another
page include the query over there and return the sum and print it in main page its not working .
Below is the main page call :
require('totals.php');
$res_easyhint_total=easyhint_totals($currentpid);
print $res_easyhint_total;
//The above is contained in a while loop and current pid gets updated each time.
Function page:
function easyhint_totals($currentpid){
require('connect.php');
$sql_easyhint_total = "SELECT sum(Coffee+Gift+Cools+Affection+Patience+Anger+EHignore) from whyangry.posts where Pid=$currentpid";
$res_easyhint_total=mysql_query($sql_easyhint_total,$con);
$res_easyhint_total=mysql_fetch_array($res_easyhint_total);
$res_easyhint_total=$res_easyhint_total[0];
return $res_easyhint_total;
}
I dont get what the error is please help.
Do you define any functions in connect.php? If not try adding this:
$res_easyhint_total=mysql_query($sql_easyhint_total,$con);
if (mysql_errno() != 0) {
echo mysql_error();
}
$res_easyhint_total=mysql_fetch_array($res_easyhint_total);
Have you checked the result from the new page there itself? I mean to say if you tried to print the result from the new page itself as like you tried from main page. Then one more thing need to concetrate that, the path of both file while including. Try to pass any other variable from the new page to main page and check if the new file included properly.
If you are able to access other variable from new page on main page and its just not returning the result from the function. Try to include connect.php on main page also and check it.
Check your connection string is returning the proper linked identifier and also check the logs if there is any error or warning from mysql like Warning: mysql_query(): [2002] No such file or directory (trying to connect via unix:///var/run/mysql/mysql.sock). In that case try to set the proper socket file location.
Have you included the file "connect.php" before?
if(!#include_once('connect.php')) {
// include connect.php
}

php querying for data just inserted...by itself

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.

PHP + Mysql queries for a real Beginner

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.

Categories