I would like to know how users can add multiple images and new data. For example on the site that I'm doing, you can make a design and when you finish you upload it to the database along with your email address title of the design, keywords ect.
I would like to know how its possible to let the user create more designs and named them all in the same database just retrieve them with an email address. I would like to make a limit of 14 designs per email address. But with the database and code that I have now, it only lets one design it just updates every time a new design is created.
Can someone show me the way on how to do this? If you need more information please ask, thank you.
Here is my code:
$query='UPDATE shirt_table SET images="'.$_FILES['file4']['name'].'", images1="'.$_FILES['file1']['name'].'", images2="'.$_FILES['file2']['name'].'", images3="'.$_FILES['file3']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
I can see that the uploaded files have different names, you'll have to list the expected file names internally as an array and loop through it that way.
Another thing you need to take care of is when the user has like 13 designs uploaded already and wants to add 4 more designs. You need to decide if you will reject all or add only one. Here is an example I believe you can modify to your taste.
/*
CREATE TABLE `shirt_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_address` varchar(50) DEFAULT NULL,
`image_path` varchar(100) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
<?php
include("lib/dbcnx.inc.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$begin = 1;
$end = 5;
$max_uploads = 14;
$sel_query = "select count(*) from shirt_table where email = '".$_SESSION['email']."'";
$result = $mysqli->query($sel_query);
echo $sel_query."<br/>";
$numrows = $result->num_rows;
$counter = 0;
if ($numrows > 0) {
$row = $result->fetch_row();
$counter = $row[0];
}
if ($counter < $max_uploads) {
$saved_dir = "designs/";
$design_files = array($_FILES['file4']['name'], $_FILES['file3']['name'], $_FILES['file2']['name'], $_FILES['file1']['name']);
$query = "INSERT INTO shirt_table (email, image_path, date_created) values ";
for ($i=$begin; $i<=$end; $i++) {
$query = $query ."('".$email."', '".$saved_dir.$design_files[$i-$begin]."', now())";
if ($i < $end)
$query = $query.", ";
}
echo $query."<br/>";
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
} else {
echo "You have exceeded ...";
$mysqli->close();
}
?>
Related
I have a website whose function is to translate subtitles from one language to another, translation is done using google widget tool , marked with red color on the image: https://ibb.co/LCWt6YV (as you can see on the left it says on google widget tool "Select Language")
there is also the option that the user can save the translated subtitle file to the database and the language in which the user translated the subtitle is automatically saved to the database,now many users do not know to use this option so they do not choose the language to translate the subtitle and just leave the option on google widget tool "Select Language".
I need some function/code so that no action will be done if Language is not chosen.
That if he does not select a language through a google widget tool and tries to save subtitles in the database, the message "Please select a language before saving subtitle" appears.
This php script is for saving subtitles into a database, now which function/code I should add in this script ?
$data = $_POST['data'];
$file_name = $_POST['xxx'];
$subtitle = $_POST['xxx'];
$language = $_POST['xxx'];
$author = $_POST['xxx'];
$ip= $_SERVER['REMOTE_ADDR'];
if (array_key_exists('HTTP_X_FORWARDED_FOR', $_SERVER)) {
$ip = array_pop(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']));
}
$data =json_decode($data, true);
foreach($data as $obj){
$subtitles1->add($obj['start'], $obj['end'],$obj['text']);
$subtitles1->save($file_name);
}
$ext = pathinfo($file_name, PATHINFO_EXTENSION);
$new_file_name_ext = time()."_".$sub."_".$lan.".".$ext;
$new_file_name = time()."_".$sub."_".$lan;
$sql_lan = "SELECT code FROM lan_code WHERE language ='$lan'";
$result_lan = mysqli_query($conn, $sql_lan);
if (mysqli_num_rows($result_lan) > 0) {
while($row = mysqli_fetch_array($result_lan)){
$lan_code = $row['code'];
}
}else{
$lan_code = $lan;
}
$sub_new = $sub.'_'.$lan_code;
$sql = "SELECT * FROM table WHERE name ='$sub_new'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
$data1 = "Unable to save subtitle, subtitle already exists with the same language in the database.";
}
else{
$query1 = "INSERT INTO table (xxx , xxx, xxx, xxx, ip)
VALUES ('$sub_new','$authors', '$lan', '$new_file_name', '$ip')";
if(mysqli_query($conn, $query1)){
copy("$file_name", "uploads/$new_file_name_ext");
//new GoodZipArchive('uploads/$new_file_name', 'upload/output_zip_file.zip') ;
$data1 = "Successful, File saved to database.";
$zip = new ZipArchive;
$new_zip = time()."_".$subtitles."_".$languages.".zip";
if ($zip->open("uploadsk/$new_zip", ZipArchive::CREATE) === TRUE)
{
$zip->addFile("uploads/$new_file_name_ext", "$new_file_name_ext");
$zip->close();
}
} else{
$data1 = mysqli_error();
}
}
echo $data1; ?>
If you want to pop up a message when no language is selected, you need to use Javascript.
In a very simplistic way you can use javascript alert() function, something like this:
echo '<script type="text/javascript">';
if(empty($language) or !isset($language)){
echo 'alert("please select a language")';
}else{
...add the rest of your code here.
}
echo '</script>';
But this results in a very ugly output. If you want something prettier you can use a plugin like sweetAlert. It's very easy to use, and a lot better then simply "alert" your message. You can take a look to sweetAlert here.
Good luck!
forgive me if this is a stupid question or has been asked a million times but I am having trouble using PHP keep in mind I am new to this language so if you guys could break it down simply that would be great.
so I have a file called createchatroom.php it takes user input and creates an SQL table with a column of usernames the main code is here:
$file = ("CREATE TABLE `" . $userstablename . "` (ID int NOT NULL AUTO_INCREMENT, username varchar(255) NOT NULL, PRIMARY KEY (ID))");
and
$sql = "INSERT INTO " . $userstablename . " (username) VALUES ('". $users ."')";
I then have another file called im.php that deals with data from 2 more files get-messages.php and update-messages.php
the im.php is basically all js so I don't really know what is happening there but this could be helpful:
xmlhttp.open("GET","update-messages.php?username=" + username + "&message=" + message,true);
xmlhttp.send();
then the update-messages.php file is:
<?php
$db = new mysqli(connection info here);
if ($db->connect_error) {
die("Sorry, there was a problem connecting to our database.");
}
$username = stripslashes(htmlspecialchars($_GET['username']));
$message = stripslashes(htmlspecialchars($_GET['message']));
if ($message == "" || $username == "") {
die();
}
$result = $db->prepare("INSERT INTO messages VALUES('',?,?)");
$result->bind_param("ss", $username, $message);
$result->execute();
i need to set the "messages" table to "usertablename" from the createchatroom.php document and have no idea how to do that. thanks for your help.
I have a quiz management system and need to fetch the data from the database and displaying the data one by one on clicking next button.
I want to use ajax to insert data into database after clicking next button by using file read and write function.
$sql=mysqli_query($con,"SELECT * FROM tbl_question WHERE setid='$set' AND status=1 ORDER BY RAND()");
while($sha=mysqli_fetch_array($sql)) {
<h4><? echo $sha['id'];?></h4>
here's simple way to do it
first get question from database then put a button to the next id
<?php
$rows = 0;
$id = isset($_GET['id'] ? (int) $_GET['id'] : 0;
$query = 'SELECT * FROM `tbl_question` WHERE `tbl_question`.`status` = 1 AND `tbl_question`.`id` = ? LIMIT 1';
$mysqli = new mysqli('localhost','user','password','database');
$stmt = $mysqli->prepare($query);
$stmt->bind_param('i',$id);
$stmt->execute();
$stmt->bind_result($id,$something,$something_else,$status);
while($stmt->fetch())
$rows++;
$stmt->close();
$mysqli->close();
if($rows === 0) {
echo 'qustion not found';
} else {
// output qustion
// button
echo '<a type="buttton" href="?id=' . $id + 1 . '">next</a>';
}
I am having trouble executing SQL via AJAX when a dropdown box is changed and would like some help if possible.
Background Info
I have been tasked with creating a daily calendar that shows all the classes ran at a gym, which at its maximum is 5 x classes of 6 (30) people per hour for 14 hours.I'm no pro and I may have created a convoluted way around this issue, please let me know if i have.
I have managed to create the view which consists of 14 columns of 30 drop down boxes (5 x classes of 6 per hour for 14 hours). Each drop down box polls the db and if an entry resides it will populate the box with the name of the bookinguser. If no booking is found it will create a drop downbox that polls the members table and presents all the members of the gym, which when changed, will hopefully book that person in. - herein lies my current issue!
Each drop down box's name corresponds to the time, group and headcount which I intend on passing to javascript function and eventually to the SQL statement. Each option's value corresponds with the memberid which will also be passed giving all the information needed to construct the SQL.
The code I have so far
HTML - snipped generated from php loops
<div id="results">
<div id="07" class="column">07:00<br/>
<div id="group1">
<select name="07:00-1-0" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
<select name="07:00-1-1" onchange="getda(this.value,this)">
<option value="none">---------------</option>
<option value="2">John Doe</option>
<option value="1">Joe Bloggs</option>
</select>
PHP
<?php
$mysqli = new mysqli("localhost", "root", "", "gym");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
function hyphenate($str) {
return implode("-", str_split($str, 2));
}
function getmembers($time,$group,$iteration)
{
$date=$_GET["date"];
$date=hyphenate($date);
$date = explode('-', $date);
$new_date = $date[2].'-'.$date[1].'-'.$date[0];
$mysqli = new mysqli("localhost", "root", "", "gym");
if ($iteration == 0){
$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1");
}
else {$result = $mysqli->query("select members.memberid, members.firstname, members.lastname from bookings inner join members on bookings.memberid = members.memberid where bookings.date = '$new_date' and time = '$time' and bookings.groupnumber = '$group' order by bookings.bookingid ASC limit 1,$iteration");
}
$rowcount=mysqli_num_rows($result);
if ($rowcount==$iteration && $iteration == 0)
{
$result = $mysqli->query("select firstname, lastname,memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
else if ($rowcount>=$iteration){
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)">';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option><option value="cancel">Cancel</option>';
}
echo "</select>";
}
else{
$result = $mysqli->query("select firstname, lastname, memberid from members order by firstname ASC");
echo '<select name="'.$time.'-'.$group.'-'.$iteration.'" onchange="getda(this.value,this)"><option value="---------------">---------------</option>';
while ($row = $result->fetch_assoc()) {
unset($firstname, $lastname);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$memberid = $row['memberid'];
echo '<option value="'.$memberid.'">'.$firstname . ' ' . $lastname .'</option>';
}
echo "</select>";
}
}
?>
JS
function getda(id,booking){
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:id
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
}
samefile.php
<?php
if(isset($_POST['get_option']))
{
inlude 'config/config.php';
$name=$_POST["get_option"];
echo "<SCRIPT>
alert('$name');
</SCRIPT>";
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
$mysqli->close();
?>
The console in chrome looks fine (below) but no records are inserted and the php alert doesn't show. I havent passed any of the variable to the SQL as I was first testing that a query executed properly
jquery.min.js:4 XHR finished loading: POST "http://localhost/gym/samefile.php".send # jquery.min.js:4n.extend.ajax # jquery.min.js:4getda # cal.php?date=140416:42onchange # cal.php?date=140416:36ListPicker._handleMouseUp # about:blank:535
Might want to look into jQuery's .change(). I think that it would work with something like below for your code. You could also have it call your function that has ajax in it as well
$( ".class" ).change(function() { //can use #id here too
$.ajax({
type: 'post',
url: 'samefile.php',
data: {
get_option:this.value
},
success: function (response) {
document.getElementById("result").innerHTML=response;
}
});
});
I see three problems in samefile.php - include spelled incorrectly, an extra semicolon, and a missing closing bracket:
<?php
if(isset($_POST['get_option']))
{
include 'config/config.php';
$name = $_POST["get_option"];
//this should be converted to parameterized queries
$sql = "insert into bookings (memberid,date,time,groupnumber) values (1,'2016-04-14','09:00',3)";
$query = mysqli_query($sql);
if(is_object($query)){
echo 'successfully inserted';
} else {
echo 'insert failed';
}
$mysqli->close();
} else {
echo 'no data to process!';
}
?>
First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>