Search the Community
Showing results for tags 'database'.
-
I'm really sorry for the poor explanation, I am absolutely not familiar with PHP. I would like to get data from my phpmyadmins 2 table, so I can display how many posts have been submitted with the same category type. One is called "posts" and the other one is called "categories". I have attached a picture to see the how it looks like. What I want is to make the category tables "id" equal to the posts tables "catagory_id", and then display how many posts have bben uploaded of each category. Here is how far I went with the coding, which is nowhere close to my expectations: <div class="stats__div"> <p class="stats__text">Categories</p> <p> <?php $all_categories_query = "SELECT * FROM categories ORDER BY title ASC"; $all_categories = mysqli_query($connection, $all_categories_query); while ($category = mysqli_fetch_assoc($all_categories)) : ?> <p><?= $category['title'] ?> <?= $category['id'] ?></p> <?php endwhile ?> <?php $all_posts_query = "SELECT * FROM posts GROUP BY category_id"; $all_posts = mysqli_query($connection, $all_posts_query); while ($posts = mysqli_fetch_assoc($all_posts)) : ?> <p><?= $posts['category_id'] ?></p> <?php endwhile ?> </p> </p> </div> I know, the coding is at the edge of being horrible, I am really sorry for that. I have tried my best. Does anyone know how to do that? I have seen that the right solution is using "array_count_values", but all the examples I have seen were lists. Any kind of help is highly appreciated!
- 11 replies
-
- php
- phpmyadmin
-
(and 3 more)
Tagged with:
-
In my database table, i have a field for price and quantity. Is there a way I could use a select to get 2 values from the database? What I mean is I will create a select field where when I select wholesale it will bring out the price and quantity and if I select retail, it will bring the price and the quantity.
-
Could someone explain to me why this connection/query succeeds <?php DB::getInstance()->query("SELECT username FROM users WHERE username=?", array("TechnoDiver")); But when I do this it comes back as failed <?php $user = DB::getInstance()->query("SELECT username FROM users WHERE username=?", array("TechnoDiver")); if($user) { echo "success -> "; } else { echo "fail -> "; } like I said I ran tests for the DB->query in the query method and it comes back successfully. It's only when I try to assign it that it comes back failed. Why??
-
Hello. I am using a form to send data to my database but when I submit the form, the data is not shown on the database. I am connected to the database so I don't think the problem lies there. Also, I have a redirect option via 'Location:' which also works. I am following online examples for the php. This is the PHP I am using: <?php include("dbcon/database-conn.php"); if (!empty($_POST)) #($_SERVER["REQUEST_METHOD"] == "POST") { $pagelinks = $_POST['pagelinks']; $title = $_POST['title']; $asideleft = $_POST['asideleft']; $body = $_POST['body']; $asideright = $_POST['asideright']; $sourceref = $_POST['sourceref']; $sourceimg = $_POST['sourceimg']; $q = "INSERT INTO pages (pagelinks) VALUES ('$_POST[pagelinks]')"; if ($_POST["add_record"]){ header('location:index.php'); exit(); } } ?> The form 'name' values match. As you can see I have tried two methods of 'Post' but neither seem to work. I would like to point out that this is an offline, local test and that I am aware that I am not using real_escape_strings, but I will, once I get the code to work. Also, I am aware of PDO, which I have tried but it is too complex, for me to solve right now. I am familiar with mysqli (including OOP), but am still learning.. I would be grateful if you can help solve my current issue. Thanks in advance for any help.
-
Hello everyone, I am a total newbie in PHP and so do here. I am trying to build a table consisting foreign key and primary key and it is showing error like "Parse error: syntax error, unexpected 'cities' (T_STRING) in line number 29". I have marked up my lines according to sublime text 3 editor. I am trying to create a database. 1 <?php 2 $servername = "localhost"; 3 $username = "username"; 4 $password = "password"; 5 $dbname = "newDB"; 7 // Create connection 8 $conn = new mysqli($servername, $username, $password, $dbname); 10 // Check connection 11 if ($conn->connect_error) { 12 die("Connection failed: " . $conn->connect_error);} 14 $firstname = $conn->real_escape_string($_REQUEST['firstname']); 15 $lastname = $conn->real_escape_string($_REQUEST['lastname']); 16 $address = $conn->real_escape_string($_REQUEST['address']); 17 $city = $conn->real_escape_string($_REQUEST['city']); 18 $country = $conn->real_escape_string($_REQUEST['country']); 19 $phone_number = $conn->real_escape_string($_REQUEST['phone_number']); 20 $email = $conn->real_escape_string($_REQUEST['email']); 22 // Attempt insert query execution 23 $sql1 = "INSERT INTO cities VALUES ('$city')"; 25 $sql2 = "INSERT INTO countries VALUES ('$country')"; 27 $sql3 = "INSERT INTO Contacts (firstname, lastname, address, city, country, phone, email) VALUES ('$firstname', '$lastname', '$address', $city, $country, '$phone_number','$email')"; 29 SELECT * FROM cities; SELECT * FROM countries; SELECT * FROM Contacts; if($conn->query($sql1) === true){ echo "City added successfully."; } else{ echo "ERROR: Could not able to execute " . $conn->error; } if($conn->query($sql2) === true){ echo "Çountry added successfully."; } else{ echo "ERROR: Could not able to execute " . $conn->error; } if($conn->query($sql3) === true){ echo "Çontact added successfully."; } else{ echo "ERROR: Could not able to execute " . $conn->error; } // Close connection $conn->close(); ?>
-
Hey guys, I wanted to share something with everyone. I hope this is helpful. This is basically a native solution to easily store PHP session data in a MySQL database. Session variables contain data that is saved for a specific user by associating the user with a unique identity. Typically, PHP would store session variables in a local file system on the server by default. While this may be acceptable to many people who are running small to moderate PHP applications, some larger applications that require load balancing would need to be run on multiple servers with a load balancer. In such cases, each server running PHP would need a way to ensure that sessions continue to work properly. One common way to achieve this is to override where PHP opens, reads, writes, and destroys the session variables so that it can perform these operations on a table inside of a MySQL database. When this is performed, the web application can gain advantages such as session management, session logging, and session interactions. I have provided my source code for your reference here: https://github.com/dominicklee/PHP-MySQL-Sessions Hope this helps someone out!
-
Here's what I am trying to do. Users Table user_id, sponsor_id, username, filled_positions, position_1, position_2, position_3, position_4, position_5 1 0 user 1 4 user 2 user 3 user 4 user 5 2 1 user 2 2 user 4 user 5 3 1 user 3 4 2 user 4 5 2 user 5 Above is a "Users" table. Here's what I am trying to do. Insert new users into the table. Say I already have the users table set up with 5 users. I want to add User 6. I want to loop through the users in the table and find the next empty position and update it with the new user id. In this scenario diagram above, the next empty position is Row 1 - position_5. The one after that is Row 2 - position_3 and then Row 2 - position_4...etc. It basically loops through rows and checks each position. So User 6 will be placed under Row 1 - position_5 and User 7 will be placed under Row 2 - position_3. How can one go on about doing that?
-
Hi I have a question about managing data from forms and database, to be exact for safe input/output data from form input fields. Do i need some filters to remove code from input if user try to insert ? When i making database table i limiting chars and same in form. Here is a piece of code i use just for test and example : // connection to database $dbh = new PDO('mysql:host=localhost;dbname=test123', 'root', ''); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // variables to insert into database $username = $_POST['username']; $password = $_POST['password']; $email = $_POST['email']; // query with prepare statements $stmt = $dbh->prepare("INSERT INTO members (username, password, email) VALUES (:username, :password, :email)"); $stmt->bindParam(":username", $username, PDO::PARAM_STR); $stmt->bindParam(":password", $password, PDO::PARAM_STR); $stmt->bindParam(":email", $email, PDO::PARAM_STR); $stmt->execute(); $lastId = $dbh->lastInsertId(); // checking if query is passed and data is inserted into dataabse if($lastId > 0) { echo 'Thank u for register.'; } else { echo 'Something went wrong, please try again.'; }
-
I want to display 10 products from each category from database, I started to display the categories but how to make displaying the products from each one. Here is the code I make so far. I'm not sure am I doing it right with doble sql select , or it can be done only with one. <div class="inner shadow"> <?php $query = 'SELECT id, title_bg AS `title_cat` FROM categories'; $result = $this->db->query($query); ?> <?php foreach ($result->result() as $row): ?> <?php $title_cat = stripslashes($row->title_cat); ?> <div class="prod-sec"> <div class="prod-head"> <h2><?= $title_cat?></h2> <div class="clear"></div> </div> <?php $query1 = 'SELECT t1.id, t1.title_bg AS `Title`, t1.text_bg AS `Text`, t1.price, t1.discount, t1.category_id, t1.promo_page, t2.id AS FileID, t2.ext, FROM products t1 LEFT JOIN products_pictures t2 ON t1.id = t2.object_id LEFT JOIN categories t3 ON t3.id = t1.category_id WHERE t1.promo_page = 0 AND t1.is_active = 1 AND t3.title_bg = '$title_cat' ORDER BY RAND() LIMIT 10'; $result1 = $this->db->query($query1); ?> <div id="classeslist2"> <ul class="home_middle_products"> <?PHP foreach($result1->result() as $row1) { $f = 'files/products_first_page/' . $row1->id . '.jpg'; if(is_file(dirname(__FILE__) . '/../../' . $f)) { $img = site_url() . "files/products_first_page/".$row1->id.".jpg"; } else { $img = site_url() . "files/products/".$row1->id."/".$row1->FileID."_2.".$row1->ext; } $title = stripslashes($row1->Title); $text = character_limiter(strip_tags(stripslashes($row1->Text)),250); $title_url = getLinkTitle($title); $link = site_url()."products/product/".$row1->id."/{$title_url}"; ?> <li style="width: 185px; height: 270px; margin-left: 3px; margin-top: 10px;"> <div class="thumb"> <a href="<?=$link?>"><img src="<?=$img?>" alt="<?=$title?>" width="182" /></a> <div class="price"><?PHP echo product_price($row1, array('show_discount' => false,"show_old_price"=>false, 'show_label' => false, 'view' => 'no')); ?> </div> </div> <h2></h2> <h2><a href="<?=$link?>"><?=$title?></a></h2> <? $text = substr($text, 0, 100); ?> <? if (strlen($text) == 100) $text .= '...' ; ?> <p><?=$text?></p> </li> <?php } ?> <div class="clear"></div> </ul> </div> </div> <?php endforeach; ?> <div class="clear"></div> </div>
-
Hello guys, i have implemebted facebook login for my website. However, tring to store the data into my local db seems to be a problem. I'll need a little assistance with the coding. Thanks in advance. BELOW IS THE ERROR MESSAGE I GET Warning: mysqli_query() expects at least 2 parameters, 1 given in /home/xxxx/public_html/3rd_party/fbOAuth/functions.php on line 16 Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /home/xxxx/public_html/3rd_party/fbOAuth/functions.php on line 17 Warning: mysqli_query() expects at least 2 parameters, 1 given in /home/xxxx/public_html/3rd_party/fbOAuth/functions.php on line 20 MY CODE <?php //require 'dbconfig.php'; $DBhost = "localhost"; $DBuser = "xxxx"; $DBpass = "xxxx"; $DBname = "xxxx"; $DBcon = new MySQLi($DBhost,$DBuser,$DBpass,$DBname); if ($DBcon->connect_errno) { die("ERROR : -> ".$DBcon->connect_error); } function checkuser($fbid,$fbfullname,$femail){ LINE 16: $check = mysqli_query("select from Users where Fuid='$fbid'"); LINE 17: $check = mysqli_num_rows($check); if (empty($check)) { // if new user . Insert a new record $query = "INSERT INTO Users (Fuid,Ffname,Femail) VALUES ('$fbid','$fbfullname','$femail')"; mysqli_query($query); } else { // If Returned user . update the user record $query = "UPDATE Users SET Ffname='$fbfullname', Femail='$femail' where Fbid='$fuid'"; LINE 20: mysqli_query($query); } }?> I'll be grateful for all the help i can get.
-
Hi All, I facing a problem with Ms Access. When i set my datatype to "Short Text", the data display perfectly. just because of limitation of "Short Text", it can only handle 255. So i decided to change the datatype to "Long Text", but the text wont display our. FYI, im using for web base data and i am using PHP language. Thanks
-
I have an html form that inserts a record into database. I also have a an html edit form that retrieves the data from the database. Normally everything works. But I just noticed that I have an issue if I use double quotes in the form field. It'll insert into the database fine. The problem arises when outputting the variable in the form field. If I echo it outside the form field, it'll show up fine with the double quotes. But inside the field, I only geta partial string. For eg. $variable_input = '5 3/4" Glitter Concealed Platform Pump'; The above will insert to the database. But if I retrieve it in the form field below, it'll return with one number only. <input type="text" name="title" value="5" /> Is there a way to fix the variable output of the wording that includes the double quotes?
- 1 reply
-
- double quotes
- data
-
(and 3 more)
Tagged with:
-
I am finding that if I have "0"(zero) value in form select option, it won't select this option or submit data. If I change this value to any other number to text, it will work. Is there a way to fix this? I have to have an option where I am able to choose to submit "0" value to the database table. <option value="0" <?php if(empty($_POST['special'])) {} else { if($_POST['special'] == 0) { echo 'selected'; } } ?> >None</option>
-
Say I have 2 tables. Table 1: Type(type_id, type_name) Table 2: Records(record_id, record_name, record_type) Under the "record_type" column, is it better to use type_id(eg. 10) or type_name(eg. Clothing & Watches)? If the answer is use the name, is it better to use the original name(Clothing & Watches) or a slug name(clothing-watches)?
-
Hello everyone, I'm going to create my school project and I really need your advice. My Project Summary I need to create a new website where the user can add new schools in my site. After creating, they can add students, add teachers, add principal and hell lot of things from their admin panel. And in the frontend they will get their own urls and can display their schools. Ex1: example.com/st_sebastians/ <------- School name. Ex2: example.com/st_augustin/ <------- School name. When the user will visit those url they will see all the contents of their respective schools. My Questions How can I create those database. For that I've thought of two methods. 1) I will create multiple database for every user/school dynamically using php and saves the record in it. (I searched on google that it is very prone to mysql injection.) 2) I will create a single database with everything related to their (school id) and stores in the single database. Example Student table id | school_id | name | roll | ---------------------------------------------- 1 | 1 | Subho | 123456 ---------------------------------------------- 2 | 5 | xyz | 236566 ---------------------------------------------- 3 | 45 | asfgf | 778219 . . . . . . . . Please note that the database are going to store whole lot of records and I don't want to it slow down. Any Help will be highly appreciated. Thank You In advance...
-
Hello I'm trying to check if 2 values exist in the database using php, Google didn't help... I need something like this : if($stmt = mysqli_prepare($db_connect,'QUERY TO CHECK IF USERNAME AND EMAIL EXIST')){ mysqli_stmt_bind_param($stmt, "ss", $user,$email); mysqli_stmt_execute($stmt); /* if username exist echo username exist if email exist echo email exist */ } else{/*error*/} thanks !
-
Hi I’m trying to develop an online application that will allow ‘Candidates’ to book on courses that “Providers” have posted. The application is going to have 4 different types of users, please see attached ‘Figure 1.4 - JobSkilla User Permissions & Roles.jpg’ all of which have different information associated with them. On first signup of a provider they will complete a company profile and a user will be created as the owner associated with that “Provider” that user will then be able to invite their team members (Team associations) to share the same “Provider” data but with restricted access to areas such as billing / invoives. I’m going to be building the application using laravel 5.2, I still want to use laravels Auth but how can I allow multiple auths? I was thinking of having a table called “Auth” that could manage the logins with a forging key to the ‘candidates’, ‘providers’ table. What’s the best way of handling multiple logins that are associated with 1 “Provider”? I’ve attached a EER diagram with the current database design this may be incomplete. I wanted to ask for some guidance with the best way to program/db design the project. I would appreciate if anyone can give me a better solution or point me in the right direction. I don't mind paying for advice. JobSkilla EER Diagram.pdf
-
Hi all, I’m building a search engine to find courses online; I wanted to ask for some guidance with the best way to program/structure the project. I’m going to be building the application using laravel 5.2 I have 3 different types of users as follows Users Course Providers Advisors All of which have different information associated with them such as Users Table first_name last_name date_of_birth email password Course Providers – this needs to have multiple logins associated with the course provider company_name address_line_1 address_line_2 postcode tel Advisors company_name first_name last_name email password I still want to use laravels Auth but how can I allow multiple auths or am I best in using roles if so how would this work? What’s the best way of handling multiple logins that are associated with 1 company? I would appreciate if anyone can give me a better solution or point me in the right direction.
-
Hi guys, I've a little problem i have a fileld in my database that i want to check. If is null to display some text else display another text. I've manage to do something like this but doesn't work. The code is below: <?php $result = @$mysqli->query("SELECT * FROM depanarecuora_clients WHERE paid_status = '$paid_status'"); while ($result = mysqli_fetch_assoc($result)) if (is_null($paid_status)) { echo "some text"; } ?>
-
Not sure why I can't get this been trying to figure it out all evening :/ The included smconfig.php contains my database password. Any ideas, I know it's gotta be easy, I must be missing something. PDO connect.php: <?php session_start(); include 'smconfig.php'; $db_host = "127.0.0.1"; $db_username = "root"; $db_pass = "$dbpass"; $db_name = "golden_wand"; // PDO CONNECT $db = new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ?> http://www.golden-wand.com/members/tester.php <?php include "../Scripts/connect.php"; $email = "test@gmail.com"; $stmt1 = $db->prepare("SELECT id, activated, username, email, password, token FROM members WHERE email=:email LIMIT 1"); $stmt1->bindParam(':email',$email,PDO::PARAM_STR); $stmt1->execute(); $count = $stmt1->rowCount(); if($count > 0){ while($row = $stmt1->fetch(PDO::FETCH_ASSOC)){ $uid = $row['id']; $username = $row['username']; $email = $row['email']; $hash = $row['password']; $activated = $row['activated']; $token = $row['token']; } } echo "Before: <br>"; echo 'UID = '.$uid; echo '<br>Token = '.$token; echo '<br>Activated = '.$activated; echo '<br>Hash = '.$hash; $activated="1"; $token = "md5($hash)"; try{ $db->beginTransaction(); $updateSQL = $db->prepare("UPDATE members SET activated=':activated' WHERE id=':uid' LIMIT 1"); $updateSQL->bindParam(':activated',$activated,PDO::PARAM_STR); $updateSQL->bindParam(':uid',$uid,PDO::PARAM_INT); $updateSQL->execute(); $db->commit(); echo "<br><br><br><br>Update Successful<br><br><br><br>"; } catch(PDOException $e){ $db->rollback(); echo "<br><br><br><br>Update Failed<br><br><br><br>"; } $stmt2 = $db->prepare("SELECT id, activated, username, email, password, token FROM members WHERE email=:email LIMIT 1"); $stmt2->bindParam(':email',$email,PDO::PARAM_STR); $stmt2->execute(); $count = $stmt2->rowCount(); if($count > 0){ while($row = $stmt2->fetch(PDO::FETCH_ASSOC)){ $uid = $row['id']; $username = $row['username']; $email = $row['email']; $hash = $row['password']; $activated = $row['activated']; $token = $row['token']; } } echo "After: <br>"; echo 'UID = '.$uid; echo '<br>Token = '.$token; echo '<br>Activated = '.$activated; echo '<br>Hash = '.$hash; ?> I own this site: http://www.golden-wand.com/phpfreaks.txt
-
Hello, I'm trying to output my database on my website but it's not working, it shows up just a blank page ( http://prntscr.com/90dfbf ), here's the code : <html> <head> <title>Untitled</title> </head> <body> <?php require_once(‘conn.php’); $sql = ("SELECT * FROM oglasi"); $query = mysql_query($sql); while ($row = mysql_fetch_array($query)) { $naziv = $row[‘naziv’]; $sadrzaj = $row[‘sadrzaj’]; echo $naziv; echo $sadrzaj; }; ?> </body> </html> And conn.php is: <?php $conn = mysql_connect(‘localhost’, ‘root’, ‘ELsk0l@r00t’) or die (mysql_error()); mysql_select_db(‘elskoglasi’) or die (‘Database selection incorrect’); ?>
-
Hi all. I don't know why this is happening. I have a scrip that backs up database. It works fine on database1 but when i use it on database2, it throws an error? Fatal error: Call to a member function fetch_row() on a non-object in $tableshema = $shema->fetch_row() ; both databases are on same domain. ps: even with another backup script still throws an error in database2 thanks ##################### //CONFIGURATIONS ##################### // Define the name of the backup directory define('BACKUP_DIR', 'cashBackup' ) ; // Define Database Credentials define('HOST', 'localhost' ) ; define('USER', 'username' ) ; define('PASSWORD', 'password' ) ; define('DB_NAME', 'database2' ) ; /* Define the filename for the Archive If you plan to upload the file to Amazon's S3 service , use only lower-case letters . Watever follows the "&" character should be kept as is , it designates a timestamp , which will be used by the script . */ $archiveName = 'mysqlbackup--' . date('d-m-Y') . '@'.date('h.i.s').'&'.microtime(true) . '.sql' ; // Set execution time limit if(function_exists('max_execution_time')) { if( ini_get('max_execution_time') > 0 ) set_time_limit(0) ; } //END OF CONFIGURATIONS /* Create backupDir (if it's not yet created ) , with proper permissions . Create a ".htaccess" file to restrict web-access */ if (!file_exists(BACKUP_DIR)) mkdir(BACKUP_DIR , 0700) ; if (!is_writable(BACKUP_DIR)) chmod(BACKUP_DIR , 0700) ; // Create an ".htaccess" file , it will restrict direct access to the backup-directory . $content = 'deny from all' ; $file = new SplFileObject(BACKUP_DIR . '/.htaccess', "w") ; $written = $file->fwrite($content) ; // Verify that ".htaccess" is written , if not , die the script if($written <13) die("Could not create a \".htaccess\" file , Backup task canceled") ; // Check timestamp of the latest Archive . If older than 24Hour , Create a new Archive $lastArchive = getNameOfLastArchieve(BACKUP_DIR) ; $timestampOfLatestArchive = substr(ltrim((stristr($lastArchive , '&')) , '&') , 0 , - ; if (allowCreateNewArchive($timestampOfLatestArchive)) { // Create a new Archive createNewArchive($archiveName) ; } else { echo '<p>'.'Sorry the latest Backup is not older than 24Hours , try a few hours later' .'</p>' ; } ########################### // DEFINING THE FOUR FUNCTIONS // 1) createNewArchive : Creates an archive of a Mysql database // 2) getFileSizeUnit : gets an integer value and returns a proper Unit (Bytes , KB , MB) // 3) getNameOfLastArchieve : Scans the "BackupDir" and returns the name of last created Archive // 4) allowCreateNewArchive : Compares two timestamps (Yesterday , lastArchive) . Returns "TRUE" , If the latest Archive is onlder than 24Hours . ########################### // Function createNewArchive function createNewArchive($archiveName){ $mysqli = new mysqli(HOST , USER , PASSWORD , DB_NAME) ; if (mysqli_connect_errno()) { printf("Connect failed: %s", mysqli_connect_error()); exit(); } // Introduction information $return = "--\n"; $return .= "-- A Mysql Backup System \n"; $return .= "--\n"; $return .= '-- Export created: ' . date("Y/m/d") . ' on ' . date("h:i") . "\n\n\n"; $return .= "--\n"; $return .= "-- Database : " . DB_NAME . "\n"; $return .= "--\n"; $return .= "-- --------------------------------------------------\n"; $return .= "-- ---------------------------------------------------\n"; $return .= 'SET AUTOCOMMIT = 0 ;' ."\n" ; $return .= 'SET FOREIGN_KEY_CHECKS=0 ;' ."\n" ; $tables = array() ; // Exploring what tables this database has $result = $mysqli->query('SHOW TABLES' ) ; // Cycle through "$result" and put content into an array while ($row = $result->fetch_row()) { $tables[] = $row[0] ; } // Cycle through each table foreach($tables as $table) { // Get content of each table $result = $mysqli->query('SELECT * FROM '. $table) ; // Get number of fields (columns) of each table $num_fields = $mysqli->field_count ; // Add table information $return .= "--\n" ; $return .= '-- Tabel structure for table `' . $table . '`' . "\n" ; $return .= "--\n" ; $return.= 'DROP TABLE IF EXISTS `'.$table.'`;' . "\n" ; // Get the table-shema $shema = $mysqli->query('SHOW CREATE TABLE '.$table) ; // Extract table shema $tableshema = $shema->fetch_row() ; // Append table-shema into code $return.= $tableshema[1].";" . "\n\n" ; // Cycle through each table-row while($rowdata = $result->fetch_row()) { // Prepare code that will insert data into table $return .= 'INSERT INTO `'.$table .'` VALUES ( ' ; // Extract data of each row for($i=0; $i<$num_fields; $i++) { $return .= '"'.$rowdata[$i] . "\"," ; } // Let's remove the last comma $return = substr("$return", 0, -1) ; $return .= ");" ."\n" ; } $return .= "\n\n" ; } // Close the connection $mysqli->close() ; $return .= 'SET FOREIGN_KEY_CHECKS = 1 ; ' . "\n" ; $return .= 'COMMIT ; ' . "\n" ; $return .= 'SET AUTOCOMMIT = 1 ; ' . "\n" ; //$file = file_put_contents($archiveName , $return) ; $zip = new ZipArchive() ; $resOpen = $zip->open(BACKUP_DIR . '/' .$archiveName.".zip" , ZIPARCHIVE::CREATE) ; if( $resOpen ){ $zip->addFromString( $archiveName , "$return" ) ; } $zip->close() ; $fileSize = getFileSizeUnit(filesize(BACKUP_DIR . "/". $archiveName . '.zip')) ; $message = <<<msg <h4>BACKUP completed ,</h4> <p> The backup file has the name of : <strong> $archiveName </strong> and it's file-size is : $fileSize. </p> <p> This zip archive can't be accessed via a web browser , as it's stored into a protected directory.<br> It's highly recomended to transfer this backup to another filesystem , use your favorite FTP client to download the file . </p> msg; echo $message ; } // End of function creatNewArchive // Function to append proper Unit after a file-size . function getFileSizeUnit($file_size){ switch (true) { case ($file_size/1024 < 1) : return intval($file_size ) ." Bytes" ; break; case ($file_size/1024 >= 1 && $file_size/(1024*1024) < 1) : return round(($file_size/1024) , 2) ." KB" ; break; default: return round($file_size/(1024*1024) , 2) ." MB" ; } } // End of Function getFileSizeUnit // Funciton getNameOfLastArchieve function getNameOfLastArchieve($backupDir) { $allArchieves = array() ; $iterator = new DirectoryIterator($backupDir) ; foreach ($iterator as $fileInfo) { if (!$fileInfo->isDir() && $fileInfo->getExtension() === 'zip') { $allArchieves[] = $fileInfo->getFilename() ; } } return end($allArchieves) ; } // End of Function getNameOfLastArchieve // Function allowCreateNewArchive function allowCreateNewArchive($timestampOfLatestArchive , $timestamp = 24) { $yesterday = time() - $timestamp*3600 ; return ($yesterday >= $timestampOfLatestArchive) ? true : false ; } // End of Function allowCreateNewArchive
-
I have been using the below method to access my database for some time now and just wanted to make sure im doing the correct thing. My application runs perfectly but im just trying to improve my programming skills. The classes are all loaded in with an autoloader so in theory using the classes below I could just call: echo User::getUsername(1); Like I say it works fine I would just love some feedback about what other people do and suggestions on something that might run better or looks cleaner. class Db { private static $db_read; private static $db_write; public static method read(){ if( self::$db_read == null ){ //create new database connection is it doesnt exist self::$db_read = new PDO(); } return self::$db_read; } public static method write() { if( self::$db_write == null ){ //create new database connection is it doesnt exist self::$db_write = new PDO(); } return self::$db_write; } class User { public static function getUsername($user_id){ $d = Db::read()->prepare('select * from user where id = ? '); $d->execute( array($user_id) ); $user = $d->fetch(); return $user['username']; } }
-
Hi there guys, I've a little problem with inserting a file name into a database table. I can't see wich is the problem. The code is bellow and i think the problem is at INSERT INTO part. <?php $path = "./cv/"; $valid_formats = array("doc", "pdf"); if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") { $name = $_FILES['photoimg']['name']; $size = $_FILES['photoimg']['size']; if(strlen($name)) { list($txt, $ext) = explode(".", $name); if(in_array($ext,$valid_formats)) { if($size<(20480*20480)) // Image size max 20 MB { $actual_image_name = time().$id.".".$ext; $tmp = $_FILES['photoimg']['tmp_name']; if(move_uploaded_file($tmp, $path.$actual_image_name)) { mysqli_query($mysqli,"INSERT INTO formular_client (client_cv = '$actual_image_name')"); } else echo "failed"; } else echo "Image file size max 20 MB"; } else echo "Invalid file format.."; } } ?> <input type="file" name="photoimg" id="photoimg" />
-
Say I am uploading an image that gets resized. The resized image is a thumb. I have it's file path saved in the database and the image itself saved in a folder. Originally I was saving both to the database and folder. But now that I think about it, do I have to save the orginal image? Wouldn't I be saving up a lot of space if I only save the thumb image? What do you think?