Articles

Affichage des articles du août, 2017

How to edit, hide and protect a single sheet whilst also keeping other sheets hidden and protected

 Question:   Thanks for taking a look at this question, I can't seem to find a solution that fits my needs. I have a spreadsheet that has many individual sheets (sheet1,sheet2,sheet3...sheetx). Sheet1 must always be visible. Sheets 3,4,5....x must be hidden and protected such that they cannot be unhidden without unprotecting the workbook. Sheet 2 must be normally hidden and protected as above but with the option of editing it after entering a password. The process of hiding and unhiding this sheet must not allow the user to see or unhide sheets 3,4,5....x i.e the user must be able to hide,unhide and edit sheet 2 by use of a password but without ever allowing the user to see sheets 3,4,5,x etc. Thanks again for having a look at this. Charlie  Answers:   You can try hiding sheet 2 (right click --> hide) and then password protecting the workbook. But before that go to VBA and paste and run this: Sub HideSheets Wo...

disable HTML when i echo a colomb

 Question:   hi users I have a table called profile it contains a colomb called info (TEXT) I use print"row[info]"; The problem is that some people enter HTML and javascript and when i use the echo it, everything shows they can even put their google ads too! How can i disable HTML thanks  Answers:   Try htmlentities() function <? echo htmlentities(row[info]); ?>

Genrating a unique ID

Image
 Question:   Hello Friends, Is there any function in PHP which i can use for generating a unique ID? Thanks  Answers:   You can generate unique id's by applying this code, $RandomStr = md5(microtime());// md5 to generate the random string echo $ResultStr = substr($RandomStr,0,12);//trim 12 digit There is another way of creating a unique id First: you create a random number using this simple script Code: <?php $numb = rand(1,999999999); echo($numb); ?> Second: You check if the number exists. If it does not exist, then, you save the new number, else, you ask the user to refresh the page to create a different ID Ofcourse this way is a little mixed up, but it should work too Why not

How to find a file is writable in PHP if it exists?

 Question:   Hello, Could you please tell me about how to find a file is writable in PHP if it exists?  Answers:   Look the details of is_writable() function in PHP manual. http://uk2.php.net/is_writable

zend framework

 Question:   I am bit confused about whether to use any framework for my php development. have you used zend frame work? how to start on this framework? what are the advantages of this?  Answers:   check the official zend framework site. you will get answer to all your questions. http://framework.zend.com/ _________________

http authontication with php

 Question: How can create a password protected area with PHP ?  Answers:   Check this php.net page: http://www.php.net/manual/en/features.http-auth.php

A chat room problem php

 Question:   Hi there, I created a php chat room There is only one thing missing I dont know how to make the data show everytime someone types something I have to reload the page to see if anything is saved in the database, so it shows in the chat room i want to to be like a real chat room, everything shows when inserted by the user How can i do that, can be done in php  Answers:   Yes , you can create chat systems in PHP. You may be able to refresh the screen on regular intervals. You can use frames to refresh middle section. There are plenty of examples online. You can download one and see how it is done.

Session is not initializing

 Question:   I can't get PHP session working on one of the windows servers. on login page i have added the following code Code: <?php session_start();   $loggedin=True;   Session_regiser("loggedin"); ?> Inside pages i tried Code: <?    echo "Logged Status:".$_SESSION['loggedin']; ?> Have you come across this problem before? Please help.  Answers:   Did you check your PHP.ini session configuration? You need to check whether session is set to be enabled in PHP.ini file.

automatically selecting list option from mysql table

 Question:   hello. I'm new to php (and coding in general) so please bare with me as I try to explain this the best I can. I have a form that I want to be able to update the data after a user has submitted it to a mysql table. I know how to make the data from the text areas reappear. What I don't know how to do is make the lists automatically select the option that was chosen the form was first submitted. anyone that can help me? If you need more info let me know, I'll try to clarify more.  Answers:   It should be simple as the textarea. When you create the drop down box , you can pre select the already submitted value. example, Code: <select name="mydropdown"> <option value="some value"<?if ($databaserow["dbfield"]=="some value"){echo " selected";}?>>display value</option> </select> YOu can post you have got thus far. we can assist you on this....

Reading XML data in PHP

 Question: Hello, I have a remote site delivers XML data to my site now i need to read that display it properly. What is the best way to do this? Is there any function to do this? Thanks  Answers:   What version of PHP are you using? If it is version 5, you can use simpleXML function and manipulate your XML data easily.

Display all rows except where a colomb = 5 !

 Question:   I have a colomb called Block in a table called amigos When i block someone, i give the colomb Block a value of 5 Now, i want to retreive data... How can i display all rows from the table amigos where Block DOES NOT equal to 5 I dont know how to write my q! Code: $con=mysql_connect("localhost", "name", "password"); mysql_select_db("database",$con); $q = "SELECT * FROM amigos ORDER BY Date DESC, Time DESC LIMIT 0, 20;"; $res = @mysql_query($q,$con); can you show me what to make q  Answers:   You can use <> operator to check this So your query will be something like: Code: $q = "SELECT * FROM amigos WHERE Block<> 5 ORDER BY Date DESC, Time DESC LIMIT 0, 20;"; $res = @mysql_query($q,$con); Let us say if you want to check more than one value, you can use NOT IN clause. Example Code: $q = "SELECT * FROM amigo...

A combo query retreiving data from database

Image
 Question: I have 2 tables: sent & profile I store emails in sent , and when i echo them, i want to if each email already exists in profile So, i did this: Code: $q = "SELECT * FROM sent ORDER BY date_sent DESC, time_sent DESC LIMIT 50;"; $res = @mysql_query($q); while($r = @mysql_fetch_array($res)) { $IsHeMember==$r[email_sent]; print "<FONT style=\"font-size:12px\" color=\"#0080FF\" face=\"Arial\">Nickname:</FONT>"; print "<FONT style=\"font-size:5px\" color=\"#FFFFFF\" face=\"Arial\">...</FONT>"; print "<FONT style=\"font-size:12px\" color=\"#000000\" face=\"Arial\">$r[nickname_sent]</FONT>"; print "<FONT style=\"font-size:5px\" color=\"#FFFFFF\" face=\"Arial\">...............</FONT>"; print "<FONT style=\...

Assigning a holw bunch of codes to a variable

 Question:   Hi I am retreiving data from the database (put inside a text area) Code: print"<textarea name=\"body\" id=\"body\" rows=\"5\" cols=\"10\"> $con=mysql_connect("localhost", "name", "password"); mysql_select_db("database",$con); $qt = "SELECT * FROM friends ORDER BY Date DESC, Time DESC LIMIT 20;"; $rest = @mysql_query($qt,$con); while($rt = @mysql_fetch_array($rest)){ many results } </textarea>"; The results are many and different but they are all inside the text area Is there a way i can create a variable which equals all these results Like $Results= Everything inside the text area  Answers:   Try this : Code: <? $con=mysql_connect("localhost", "name", "password"); mysql_select_db("database",$con); $qt = "SELECT * FROM f...

A little problem reteiving data from databse and using if fu

 Question: I have a table called amigos, which contain thousands of FriendIDs I did this code, which will check if a specific friendID is in the latest 15 $qcheck = "SELECT * FROM amigos WHERE FriendID=$FriendID ORDER BY Date DESC, Time DESC LIMIT 0, 15;"; $rescheck = @mysql_query($qcheck,$con); if(mysql_num_rows($rescheck)>0){ print"Your ID is already in the latest 15!"; }else{ print "You ID is not in the latest 15"; } but it always gives the result that is in the latest 15 even if it is far earlier Why, did i do anything wrong in the query guys?    Answers:   hi, Logically your query is wrong. U can try somethin like: Code: SELECT * FROM amigos WHERE FriendID=$FriendID AND ID IN ( SELECT ID FROM amigos ORDER BY Date DESC, Time DESC LIMIT 0, 15) I hope you will have a primary key field called ID

Using if function in PHP and banning Emails

 Question:   I have a table called blocked in which, i store many Emails which are blocked I want to use an if function, which states if the user is blocked or not So, the user submits his Email from a Form field called Email I did... $BlockedEmail=$r[Emails]; ///Colomb name in database if ($Email=='???'){ print "Sorry, your Email has been blocked" }else{ print "Welcome"; In the place where i put ???? i dont know what to do I want to say, if the Email is any of the blocked Emails in the database, then, print Sorry  Answers:   What about querying the database table and find if the email in blocked list? It may be some thing like $query="select * from block where email='useremail'" $result=mysql_query($query); if(mysql_num_rows($result)>0){ echo " Sorry you are blocked!"; }else{ echo "Welcome"; }

PHP While Traveling

 Question:   I know this is going to be a really simple answer to a really dumb question, but I will be traveling this weekend (and won't be driving!). I would like to do some PHP coding while on the road, but won't be able to upload my files to test them on the server. How can I test php / mysql with only my laptop and no internet? Thanks!  Answers:   Download VHCS VM from http://www.vmware.com/appliances/directory/370 Install vmware player run the VHCS vm using Vmware player. You have got a webserver inside your laptop.

need help with session variables

 Question:   I have edited the below phrase repeatidly and cannot get it to work. What do I have wrong here? Code: if( isset($_SESSION['current_page']))    {    //print( "email_call_page contains $_SESSION['current_page'] <br>" );    print( "if is true <br>" );    { else    print( "session variable current_page is not set <br>" );  Answers:   what is the error that you are getting? a compilation error or a problem with the session variable? BTW, the '{' is misplaced in the code. Code: if( isset($_SESSION['current_page'])) {    //print( "email_call_page contains $_SESSION['current_page'] <br>" );    print( "if is true <br>" ); }//<-- corrected else {    print( "session variable current_page is not set <br>" ); }

validate email using php

 Question: Hi, I have to validate email in PHP. What is the regular expression syntax for doing this? Thanks    Answers:   You can use ieregi regular expression to validate email address: Code: <? if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9- ]+)*(\.[a-z]{2,3})$", $mailvar) {   echo "not a valid mail"; } ?>

VBA_Excel Into Access

 Question:   I am trying to use VBA to import an excel file (which I have on a local drive) into Microsoft Access. Currently this is the code that I have, but I know that it is incorrect: DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "example", selectFile, True Can someone please help?  Answers:   The complete template for a spreadsheet transfer is as such: expression.TransferSpreadsheet(TransferType, SpreadsheetType, TableName, _ FileName, HasFieldNames, Range, UseOA) where TransferType , in your case, is acImport and SpreadsheetType is acSpreadsheetTypeExcel12Xml (assuming it is, in fact, an Office 2010 XML file). TableName would be the name of the table in the Access database that you're importing your spreadsheet into, FileName is the name (including the full path) of the file you're importing. HasFieldNames refers to whether or not the first row in your spreadsheet contains field names or not. Range would be us...

Code for copy data using VbA code in Excel

 Question:   How can I fix the below code for below snapshots? I have tried below code Dim Rng3 As Range Dim Rng5 As Range For Each Rng3 In CurCell_1 For Each Rng5 In CurCell_3 lLFs = VBA.Len(Rng3) - VBA.Len(VBA.Replace(Rng3, vbLf, "")) If lLFs > 0 Then Range("B27").Select Selection.Copy Sheets("AccountModule").Select Range("AY2").Select Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _ False, Transpose:=False End If Next Next but the same is not working.  Answers:   1 down vote I suggest you use a different kind of routine like this one: Sub separ8(src, trg) Dim r As Range, ar For Each r In src.Rows ar = Split(r.Cells(1, 2), Chr(10)) For Each el In ar trg.Value = r.Cells(1, 1) trg.Offset(0, 1) = el Set trg = trg.Offset(1) Next el Next r End...

Select/deselect a check box group using JavaScript

This article example shows how to implement select/deselect a check box group using one main check box. Example given here has tested only on IE and Firefox so you may want to try and test it before using this in your web pages . Please post your comments on this article if you have any. Code: <script type="text/javascript"> <!--  function CheckORUnCheck (chkBox) {      var arrVals = document.getElementsByTagName("input");      for (x=0; x<arrVals.length; x++) {          if (arrVals[x].type == 'checkbox') {            if (chkBox.checked==true){              // select mode              arrVals[x].checked = true;           }else{           //deselect mode              arrVals[x].checked = false;...

Simple Contact us form in PHP

Most of the web sites have a contact us form which takes the user input and send it to mail box. Small web sites can use the example provided in this article and modify it according to their requirements. Here is the complete code to send emails. Code: <?php ob_start(); ?> <!-- Add your header here --> <html> <head>       <title>Contact Us</title> </head> <body> <?   //set up varible   $date=date('Y-m-d');      $to="webshiju@hotmail.com";        $subject="Contact us form on $date";       $show_form=true;   if ($_POST['action']=="Submit"){         $email=$_POST['email'];     $comment=$_POST['comment'];    if(!eregi('^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,3}))$', $email)){    //user entered a wrong email address      ...

Using replace functions in PHP

It is important that PHP programmers should know well about functions available to manipulate text strings in PHP. PHP has many powerful functions for string manipulation which are handy when working with database or file handling projects. PHP offers few string replace functions and in this article we can have a look at some of these functions. If we need to replace a simple string, we can use str_replace() or str_ireplace() . str_replace() This will replace given string within a string. This may be case sensitive Example, Code: <?php   echo str_replace("oldword", "newword", "This should be my string and has oldword in it."); ?> str_ireplace() This is case-insensitive version of str_replace() . Example, Code: <?php   echo str_ireplace("oldword", "newword", "This should be my string and has oldword in it."); ?> If you wo...

Calling client side scripts using in server controls.

It is a common question in ASP.net forums about how to call the VB Script or Java script in server controls so i thought to publish an example here. In normal html tag we used to call the scripts like <input type ="button" name="txt" onclick="Alert('This is a test');" /> But in ASP.Net server controls we do not have the design mode attribute to add client side scripting like this. <asp:Button ID="Button1" runat="server" Text="Button" /> In order to add the onClick event in this text box , attribtes need to add in code behind. Syntax for this is: Servercontrol.Attributes.Add("key","value"); Example, Code:  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load         Button1.Attributes.Add("onClick", "Alert('This is a test');");     End Sub It is also possible to add a...

Protect MySQL database against SQL Injection in PHP applications

SQL Injection is one of the major security risks of PHP applications if it is not written properly without giving much attention to SQL query code in PHP. SQL Injection means sometimes hackers can execute SQL statements and crash the database from client browser and steal the valuable data. Sometimes even destroy database completely. For understanding what is SQL Injection, look at the sample code below. Code: <?php $db_name="dev";// Database name $connection=mysql_connect("localhost","root","") or die("I couldn't connect"); $db=mysql_select_db($db_name) or die("I couldn't select your database"); $SQL = �select * from customer where id=�.$_Get[�id�]; Mysql_Query($SQL, $connection); ?> This script is written for executing a SQL statement to select the entire data from customer table where id is equivalent to the value of the query string that is $_Get[�id�] which is pass...

Pagination code in ASP.Net

Imagine you have a webpage which is showing rows retrieved from a database table. What do you do to show the table contains hundreds and thousands of rows? You can�t show all those data in a single page. So you may want to split the data into multiple pages. For example, when we do a search in google.com, it doesn�t show all searched results in a single page. It will split the results into multiple pages which look like this: Previous 1 2 3 4 5 6 7 8 9 10 Next We can do Pagination in Asp.Net DataGrid easier than other web technologies like PHP, JSP etc. This is because of built in feature for pagination provided by Asp.net Datagrid using its AllowPaging property. But there is a big drawback in it is the performance because it keeps all the records in the memory and when the no of records increases it makes the data retrieval in the web page slower. So use the Datagrid only if it contains a few records. So in the case of pagination in .net it is better to writ...

Database connection pooling in ADO.Net

Imagine a situation that multiple users are connecting the same database through our application. In an application establishing a database connection and logging into it is a time consuming activity. It needs several seconds for every time it establishes a connection. So opening and maintaining a database connection for each user is not an ideal solution. When the number of users increases, and if the system�s memory set is limit, probably it leads to a system crash. This problem can solve through connection pooling. A connection pool is a cache or pool of database connections maintained by the application so that the connections can be reused when the database receives future requests for data. Establishing once and reserving it for future request can essentially improve the overall performance of the application. In connection pooling, after a connection is created, the connection object is placed in the pool. When a simultaneous connection request is made later, ...

Passing array value to database stored procedure

Some of the applications may need to update the database procedure with bulk records at one go. Instead of doing a loop calling the stored procedure, an array value can be passed to the stored procedure and update the database. I use this procedure to insert or update database values. Code: Create procedure usp_updaterecords (@ArrayInput varchar(8000)) as BEGIN     SET NOCOUNT ON     DECLARE @Row varchar(10), @Position int     SET @ArrayInput = LTRIM(RTRIM(@ArrayInput))+ ','     SET @Position = CHARINDEX(',', @ArrayInput, 1)     IF REPLACE(@ArrayInput, ',', '') <> ''     BEGIN       WHILE @Position > 0       BEGIN          SET @Row = LTRIM(RTRIM(LEFT(@ArrayInput, @Position - 1)))          IF @Row <> ''          BEGIN        ...

How to use .Net components in PHP

A component is a unit of reusable code. Components reduce our application development time and they assemble our application source files into one executable unit. Assemblies are building blocks of a .net application. Components are packaged in assemblies. They can exist in the form of DLL�s or exe�s. The basic difference between a .dll file and .exe file is that a .dll file cannot execute independently. They can only include in our application and reuse the functionalities provided in it. An exe file can execute independently. Another difference is that an exe file have an entry point. That is they can have a main method. A dll file does not have an entry point. They can contain classes, interfaces etc. Assemblies are 2 types. Shared and Private. In a .net application, any component placed in the application�s bin directory is automatically available to that particular application. They can be called as private assemblies. But if you want to use that component in p...

Using DATE functions in Coldfusion

There are some useful date functions in Cold Fusion which makes life easy for developers when working date and time date. In this article, we can take a look at few date functions and examples for those functions. Now() This function will return the current date and time from the cold fusion server. Examaple, Code: #now()# Dateformat() This is the function to format a date in any format given in the second argument. It takes two arguments first argument date and second one is mask Example, Code: #dateformat(now,"dd-mm-yyyy")# Following are the possible mask you can use with dateformat(). Code: Day of the week : d , dd, ddd , dddd Month : m, mm, mmm, mmmm Year : y, yy ,yyyy Timeformat() This function format a time based on mask passed to the function. Example, Code: #Timeformat(now,"hh:mm:ss")# Following are the possible mask you can use with dateformat(). Code: Hours : h (12-hour clock) , hh (12-hour clock), H, ...

Currency Conversion in PHP Script

Recently I have implemented a shopping cart for a site and integrated a payment solution with a payment gateway from one of the popular payment service, CCAvenue . I wanted to share my experience on this project. I thought this may help you when you do similar IT projects. We had to register our client�s account on CCAvenue as Indian e-merchant and not as Global e-merchant to start the project. The payment processing and settlement of currencies was done in Indian Rupees only. We were able to pass the amount from our shopping cart to this payment service only in Indian Rupees. Our client�s requirement was to show the amounts of products in shopping cart purely on US Dollar. We found that transferring the account from Indian e-merchant service to Global e-merchant service will take some time and it will be consuming as well. We couldn't wait for that and we needed an urgent solution. So we had to convert the US Dollar amount to Indian Rupees before transferri...

Using REPLACE function in SQL Server

This is a small article explaining how to use REPLACE function in SQL queries. In one of my recent projects I had to replace all the - (hyphens) from the search results and i thought share my experience with you. Syntax for replacing a string is Code: REPLACE (string, substring1, substring2) This function will replace all the occurrences of the sub string 1 with a substring 2. So replacing � hyphens from a column result will be something like Code: SELECT REPLACE(ColumnName,�-�,��) as Col1 FROM TableName This function can be used in with WHERE condition as well For example, Code: UPDATE TABLENAME SET  REPLACE(ColumnName,�-�,��) =�somevalue� Hope these examples help in your SQL queries. Thanks

File download using Coldfusion

In some applications, we may require to give file download to users. In order to protect the files from hackers, you may want to hide the actual path of the file and just stream the data to the user. This small script can stream the data to client browser based on the file name. You may be able to customise this for your application. You need to change two parameters to use this script. First one is the filename and second one is the file directory path. Code: <cfparam name="url.filenamename" default=""> <cfset url.filename="/paththo/file"> <cfif trim(url.filename) neq "">  <!--- mime type --->    <cfset strFileExt=mid(url.filename,find(".",url.filename,len(url.filename)-3)+1,3)>    <cfswitch expression="#strFileExt#">     <cfcase value= "asf">           <cfset lcl_content = "video/x-ms-asf">     </cfcase>   ...

Reading Microsoft Excel data in ASP.Net

Reading Microsoft Excel sheet is quite simple in ASP.net. There are many ways to do CSV file reading in .Net. In this article I�m going to show an example which will get the data from excel sheet and display them in a Data GridView control . First create a front-end design using your IDE. Default.aspx Code: <%@ Page Language="VB" AutoEventWireup="true" CodeFile="Default.aspx.vb" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">     <title>Read Excel Sheet</title> </head> <body>     <form id="form1" runat="server">      <div>          <asp:GridView ID="GridView1" runat="server">          </asp:GridView>               ...

XAJAX with PHP – The future of web development

XAJAX is a class library or framework written purely on PHP that allows you to easily create powerful, Web-based, Ajax applications or plugins. You can download xajax framework from http://sourceforge.net/projects/xajax/ XAJAX is easy to impement. You need to just include XAJAX library, instantiate the xajax object, and register the name of function (or an object or class method) which you want to call from XAJAX framework. xajaxResponse() is an object to return the results of our requests as XML formats. Then call that particular function you want from xajax framework through your HTML or javascript. That's it. XAJAX takes care of most everything else. You just need to write the PHP functions and returning XAJAX XML responses from them, which is made extremely easy by the xajaxResponse class. Code: <?php include './xajax/xajax_core/xajax.inc.php'; $xajax = new xajax(); $rqstAdd =& $xajax->register(XAJAX_FUNCTION, 'ad...