Repeat PHP code - php

I have this code that I would like to know if there is an easier way to have it repeated. I have about 60 of these and I will always be adding more so it would be nice if someone could help me figure out a loop or something so that I won't have to manually add each one. Each of these is making a link to a download, so I am guessing I will probably have to use the variable name as the file name. The file name 01 Intro.mp3 is what tells where the download is, so I am guessing to make this work I would also have to change that to the variable name.
Here is the code I use to get the variable names.
while ($row = mysqli_fetch_array($resultstwo))
{
extract($row);
}
Here is the code that I would like to be repeated. I included two of them.
<?php
if ($intro ==1) {
$strKey = createKey();
mysqli_query($resDB,"INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', '01 Intro.mp3', '".(time()+(60*60))."')");
echo "<a href='download.php?key=$strKey'>Intro</a>";
}
?>
<?php
if ($fightingfires ==1) {
$strKey = createKey();
mysqli_query($resDB,"INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', '02 Fighting Fires.mp3', '".(time()+(60*60))."')");
echo "<a href='download.php?key=$strKey'>Fighting Fires</a>";
}
?>

I would suggest having some variables within the database if not already included, such as:
id,caption,filename
--------------------
1,Intro,01 Intro.mp3
2,Fighting Fires,02 Fighting Fires.mp3
Here is the SQL query for creating this table:
CREATE TABLE `music` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`caption` varchar(32),
`filename` varchar(32),
PRIMARY KEY (`id`),
UNIQUE KEY `uc_filename` (`filename`)
);
As well as some test data that you can also insert.
INSERT INTO `music`(`caption`,`filename`) VALUES('Intro','01 Intro.mp3'),('Fighting Fires','02 Fighting Fires.mp3');
Assuming the user table follows the current format:
id,username,intro,fightingfires
-------------------------------
1,michael,1,NULL
2,dave,NULL,NULL
I believe that it should be altered to show this instead:
id,username,music_id
--------------------
1,michael,1,
2,dave,NULL
The structure of this table can be written as:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(32),
`music_id` int(11),
PRIMARY KEY (`id`),
KEY `music_id` (`music_id`),
CONSTRAINT `users_music_id_ibfk_1` FOREIGN KEY (`music_id`) REFERENCES `music` (`id`) ON DELETE CASCADE
);
Now when a music row is deleted from the music table, any users wishing to download that music will also be removed.
Try to query the database like this now:
$resultstwo=$mysqli->query("SELECT `music_id` FROM `users` WHERE `username`='michael'");
Change the username based on which user is logged in, but I imagine you have that under control.
Then you can manage the data better like this:
while ($row = mysqli_fetch_array($resultstwo)) {
$strKey = createKey();
mysqli_query($resDB,"INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', '".$row['filename']."', '".(time()+(60*60))."')");
echo "<a href='download.php?key=$strKey'>".$row['caption']."</a>";
break;
}
Then you can better manage downloading of music by adding or deleting columns from the table above.

I don't understand completely what you want to do, but I assume the following:
You're reading from a table which contains filenames, and for each file you want to create the entry in the table downloads, as well as output the HTML link to the download.
Here's how you could do it, but it looks like you need to change your table structure for the files to something like the following:
id track_no filename
In that case, you could do everything directly in the first loop:
<?php
while($row = mysqli_fetch_array($resultstwo))
{
$strKey = createKey();
mysqli_query($resDB,
"INSERT INTO downloads (downloadkey, file, expires)
VALUES(
$strKey,
$row['track_no']." ".$row['filename'],
(time()+(60*60))
)");
echo "$row['filename']";
}
If that doesn't answer your question, you should tell us more about your table containing the files.

Building on other answers, here's how to do the loop and hit the database only once.
$query = "INSERT INTO downloads (downloadkey, file, expires) VALUES ";
while ($row = mysql_fetch_array($resultstwo)) {
$strKey = createKey();
$time = time()+(60*60);
$query .= "('{$strKey}', '{$row['filename']}', {$time}),";
echo "<a href='download.php?key=$strKey'>{$row['caption']}</a>";
}
$query = substr ( $query, 0, -1 ); // Remove the last comma.
mysql_query ( resDB, $query );
The end result of the query will be something like:
INSERT INTO downloads (downloadkey, file, expires) VALUES
('adfsdfgsdgs', 'Bladerunner.avi', 12345678),
('dfghfyadfsg', 'How_I_met_your_mother.avi', 12345678),
('34t34t3t', 'Simpson_the_movie.avi', 12345678),
('taert43te', '{$row['filename']}', 12345678),
('at43t3t', '{$row['filename']}', 12345678),
This will insert all the values into mysql using this one query only.

How about:
function f($condition, $filename, $prettyname)
{
if ($condition)
{
$strKey = createKey();
mysqli_query($resDB,"INSERT INTO downloads (downloadkey, file, expires) VALUES ('{$strKey}', '$filename', '".(time()+(60*60))."')");
echo "<a href='download.php?key=$strKey'>$prettyname</a>";
}
}
And then simply recover the values from the database, a file or just an array as you see fit.

Related

PHP update mysqli only works until closing browser

I have a question about the update function in mysqli.
For school, I'm trying to create a click counter for my website which counts how many times a user has visited a certain page.
So far I've come up with this:
<?php
/*
* ToDo: Check why number of clicks goes back to two when completely
* refreshing page.
*
*/
include("init.php");
session_start();
//Count variable
$clicks = 0;
//Query for checking if there are any entry's in the database
$query = "SELECT * FROM `beoordelingen`.`clickcounter` WHERE `game_id`={$id}";
$result = $conn->query($query);
//If query returns false
if (!mysqli_num_rows($result)) {
//Create entry in database
$insert = "INSERT INTO `beoordelingen`.`clickcounter` (`ID`, `game_id`, `clicks`) VALUES (NULL, '1', '1');";
$createEntry = $conn->query($insert);
}
//If query returns true
else {
//Setting the number of clicks equal to $clicks
while ($data = $result->fetch_assoc()) {
$clicks = $data['clicks'];
}
//Insert new number into database
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$insertInto = $conn->query($sql);
//Echo current number of clicks
echo $clicks;
}
?>
The actual problem is that my update statement doesn't seem to work properly. If anyone would be able to spot why it doesn't work I'd be very happy.
The database is as following;
Beoordelingen <- Database
clickcounter <- Table which has the following three columns:
1. ID
2. game_id
3. clicks
The scripts does add an entry into the databse with click count 2. So when I reload the page it says 2. And when refreshing it counts up, but doesn't update the table.
Thanks! If anything is unclear please ask me!
Theoretically you should be able to do all of it in one query if game_id is unique.
Given the following table structure the sql query below will insert if the relevant record does not exists and then update if it does.
create table `clickcounter` (
`id` int(10) unsigned not null auto_increment,
`game_id` int(10) unsigned not null default '0',
`clicks` int(10) unsigned not null default '0',
primary key (`id`),
unique index `game_id` (`game_id`)
)
engine=innodb;
The trick is setting the indices on your table correctly ~ initially you don't know the value of the ID and I would guess that is an auto increment primary key? So, set a unique key on game_id...I hope it helps!
/* Could even change `clicks`='{$clicks}' to `clicks`=1 in initial insert */
$sql="insert into `clickcounter` set `clicks`='{$clicks}', `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
<?php
include("init.php");
session_start();
/* Where / how is "$id" defined? */
/* insert new record / update existing */
$sql="insert into `clickcounter` set `clicks`=1, `game_id`='{$id}'
on duplicate key update
`clicks`=`clicks`+1;";
$result = $conn->query( $sql );
/* retrieve the number of clicks */
$sql="select `clicks` from `clickcounter` where `game_id`='{$id}';";
$result = $conn->query( $sql );
while( $rs=$result->fetch_object() ) $clicks=intval( $rs->clicks );
echo 'Total clicks: '.$clicks;
?>

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

Create a table with a name taken from a variable in php and append a string to it

I am trying to create a table with the name taken from a variable in php.
The table name also would need to be appended with a string.
For example, $ProjectID is taking an input from an html form.
I would need to create different tables for different iterations of the project review.
So, when the project is submitted for the first time and if the project ID is 12345, a table needs to be created as P12345-1st-Review or P12345_1st_Review.
How do I do that?
I am able to create the table with the input from $ProjectID, but I am not able to append 1st_Review to it.
Any help?
The code that I have used is as below:
$ProjectID=$_POST['ProjectID'];
$sql = "CREATE TABLE $PID._1st_review (No int(4) primary key auto_increment, findings longtext);";
mysqli_query($dbconnect, $sql);
if (mysqli_error($dbconnect))
{
ECHO "Error Description:".mysqli_error($dbconnect);
}
You can always do:
$ProjectID = $_POST['ProjectID'];
$ProjectID.= "_1st_review";
Then perform the query.
Here you go.
Although I'm not sure if your query is correct(the No int thing seems vague)
<?php
$ProjectID=mysql_real_escape_string($_POST['ProjectID']); //Make sure to escape this
$sql = "CREATE TABLE ".$ProjectID."_1st_review (No int(4) PRIMARY KEY auto_increment, findings longtext);";
mysqli_query($dbconnect, $sql);
if (mysqli_error($dbconnect))
{
echo "Error Description:".mysqli_error($dbconnect);
}
?>

Invalid arguments passed in implode()

So I have a CSV file that I'm trying to make into a table.
I gave up on the import GUI after too many errors, and am trying to accomplish the import through a php file.
//create table with KNOWN values
mysql_query("CREATE TABLE uri_faculty
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
id INT(15),
lname VARCHAR(50),
fname VARCHAR(50),
mi VARCHAR(3),
Spc_Title VARCHAR(50),
title VARCHAR(50),
deptid INT(5),
dept VARCHAR(50),
degree1 VARCHAR(10),
earned1 INT(4),
school1 VARCHAR(75),
degree2 VARCHAR(10),
earned2 INT(4),
school2 VARCHAR(75),
degree3 VARCHAR(10),
earned3 INT(4),
school3 VARCHAR(75),
degree4 VARCHAR(10),
earned4 INT(4),
school4 VARCHAR(75),
degree5 VARCHAR(10),
earned5 INT(4),
school5 VARCHAR(75),
degree6 VARCHAR(10),
earned6 INT(4),
school6 VARCHAR(75)
)");
//Get CSV file
$getfile = 'faculty_delim2.csv';
$csvfopen = fopen($getfile, "r");
//loop to fill csvget with arrays
for($i=0;!feof($csvfopen);$i++){
$array = fgetcsv($csvfopen);
$insert = implode("','", $array);
//to exclude the first 2 lines (titles of document)
if($i>=1){
//values to be inserted into SQL are displayed
//echo var_dump($array[$i])." <br> ";
$sqlval = $insert;
// var_dump($sqlval);
//the while loop will constantly place values into the database until the file is finished
mysql_query("INSERT INTO uri_faculty (id,lname,fname,mi,Spc_Title,title,deptid,dept,
degree1,earned1,school1,
degree2,earned2,school2,
degree3,earned3,school3,
degree4,earned4,school4,
degree5,earned5,school5,
degree6,earned6,school6,) VALUES ('$sqlval')
");
}
}
fclose($csvfopen);
echo "complete";
?>
I keep getting an error saying that implode is receiving incorrect parameters, yet every bit of documentation I've found says that I am correct.
I changed the permissions of the file, and it is in the right place.
Instead of this:
for($i=0;!feof($csvfopen);$i++){
$array = fgetcsv($csvfopen);
I would write this:
while ($array = fgetcsv($csvfopen)) {
The loop will automatically finish when there are no more rows to read. Your error is probably an edge case, where the file still thinks it is not at feof but in spite of that, there are no more rows, and fgetcsv returns false.
By the way, two other issues:
You will run into another error soon:
. . . degree6,earned6,school6,) VALUES . . .
You must not put a comma after the last column. Write this instead:
. . . degree6,earned6,school6) VALUES . .
You are wide open to SQL injection issues. What happens when one of your CSV fields contains an apostrophe? You should learn how to use PDO with query parameters. Or failing that, use escaping:
$insert = implode("','", array_map('mysql_real_escape_string', $array));
Finally, you should consider skipping fgetcsv and use LOAD DATA INFILE. Then all your CSV issues, and escaping issues just go away.
mysql_query("LOAD DATA LOCAL INFILE 'faculty_delim2.csv' INTO TABLE uri_faculty IGNORE 2 LINES");

Check whether records exist in database

I know there are various offered solutions for this topic posted on this site, and I checked (and used) some of those solutions. Nevertheless, I can't figure out why my code below does not work, probably because I'm a starter with respect to php and sql programming ;-(
The code is supposed to add a record with 3 fields (FirstName, LastName, Age) in a table (persons), but only if the record does not already exist. Therefore a check on existing FirstName and Lastname fields is performed. But in case of existing record the condition of the if statement still seems to be true and a copy of the existing record is still inserted into the database. What do I miss?
Thanks in advance for the help.
//check whether item does not exist in database
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='$data[1]' AND LastName='$data[2]'";
$result = mysql_query($query);
if($result && mysql_num_rows($result) > 0)
{
echo " <br> record exist";
}
else
{
$theage = (int)$data[3]; //! for conversion of integer values
$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$data[1]','$data[2]','$theage')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
}
You have to use {} around array values in query
$query ="SELECT FirstName,LastName FROM persons
WHERE FirstName='{$data[1]}' AND LastName='{$data[2]}'";
Also your INSERT query runs on mysqli and SELECT query runs on mysql. You have to use only 1 not both and use below code with mysqli.
$result = mysqli_query($con,$query);
if($result && mysqli_num_rows($result) > 0)
{
echo " <br> record exist";
}
May be this query will help you:
INSERT INTO persons (FirstName, LastName, Age)
SELECT * FROM (SELECT FirstName,LastName) AS tmp
WHERE NOT EXISTS (
SELECT FirstName, LastName FROM persons WHERE WHERE FirstName='$data[1]' AND LastName='$data[2]'
) LIMIT 1;
Check your connection
In first query you have used
mysql_query
then in second case at the time of insert you use
mysqli_query
From the database perspective, modify your Person table design by setting a UNIQUE KEY for the necessary fields i.e :
CREATE TABLE `Persons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`FirstName` varchar(255) NOT NULL,
`LastName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `unique_FirstName_LastName` (`FirstName`,`LastName`) USING BTREE
)ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;
Do a normal insert, handle the duplicate error
[Err] 1062 - Duplicate entry 'jk-kenneth' for key 'unique_FirstName_LastName'

Categories