473,386 Members | 1,793 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How can i reuse function

luckysanj
Hello Sir,

I have an one problme when inserting data.

I want to insert data through function cuz of reuse function.

Expand|Select|Wrap|Line Numbers
  1. function add_rec($tbl,$flds,$val)
  2.     {
  3.     $sql="insert into $tbl ($flds) values($val)";
  4.     $sql_result=mysql_query($sql) or die(mysql_error());
  5.     return($sql_result); 
  6.     }
I have create this function on one file.

& i want to use this function when we insert data from multiple tables or different fields.

So can u guide me How can i reuse this function when we insert multiple data from multiple fields.

Like: Employee Records from one table to one database table.tbl_emp_record
CompanyInfromation from one table to another database table eg: tbl_company
Jul 23 '09 #1
20 3396
dlite922
1,584 Expert 1GB
A function cannot magically guess your SQL format, you have to pass it all the values, like you have. Except in your example you don't passin the MySQL link (a database resource created by calling mysql_connect())

pass that in like mysql_query($sql,$dbLink) and you'll be good to go.

You should look into a DA (Data Accessor) class and design your app with OOP. But that's after you have a good understanding of PHP.



Dan

PS -- You $fld and $val, I assume will be arrays, need to be implode()ed with a comma and quotes like this: $fieldStr = "'" . implode("','",$fld) . "'"; THEN insert it into the query. same with $val.
Jul 23 '09 #2
Canabeez
126 100+
As dlite922 said, you should use a mySQL link for this to work, I'd do something like:

Expand|Select|Wrap|Line Numbers
  1. $dbLink = mysql_connect('YOUR_HOST','YOUR_USER','YOUR_PASS');
  2. mysql_select_db('YOUR_DATABASE', $dbLink);
  3.  
  4. function addData($TableName,$Fields,$Values)
  5. {
  6.     global $dbLink;
  7.     $query = "
  8.         INSERT INTO {$TableName} (".(is_array($Fields)?implode(",",$Fields):$Fields).") 
  9.                           VALUES (".(is_array($Values)?implode(",",$Values):$Values).");
  10.     ";
  11.     return ($result = mysql_query($query, $dbLink)) ? $result : false;
  12. }
  13.  
Jul 23 '09 #3
Expand|Select|Wrap|Line Numbers
  1. $link=mysql_connect("localhost","root","") or die("Connection Failed");
  2. mysql_select_db("query",$link) or die("Failed Connecting To Database");
  3. $tblname='tbl1';
  4. $field=array('name','address');    
  5. $data=array($name,$address);
  6. echo $success=InsertData($tblname,$field,$data);
  7. function InsertData($TblName,$Fields,$Values)
  8. {
  9. global $link;
  10.  $query="INSERT INTO $TblName(".(is_array($Fields)?implode(",",$Fields):$Fields).") VALUES(".(is_array($Values)?implode(",",$Values).")";
  11. return ($result=mysql_query($query,$link))?$result:false;
  12. }
I Use this one function but can not work. plz where is my problem ..
Jul 24 '09 #4
I used this above method like:

Expand|Select|Wrap|Line Numbers
  1. $fieldStr = "'" . implode("','",$fld) . "'"; 
And It works very nicely & i feel happy. But have done this above second method too. but it doesn't work means it gives error on line number 10 like this ";" error.

I want to know or solve through Canabeez Newbie method for my good programming. So plz as possible give us error free codes.

Thank You.
Jul 24 '09 #5
Expand|Select|Wrap|Line Numbers
  1. $field=array('name','address');    
  2. echo $new=is_array($field)?implode(",",$field : $field);
In the above code this error is occur.

Expand|Select|Wrap|Line Numbers
  1. Parse error: syntax error, unexpected ':' in D:\xampp\htdocs\my\test\query\check.php on line 2
.

Plz where is my problem..
Jul 24 '09 #6
Dormilich
8,658 Expert Mod 8TB
",",$field : $field is not a correct call for implode(). you probaby meant
Expand|Select|Wrap|Line Numbers
  1. $new=is_array($field)?implode(",",$field) : $field;
Jul 25 '09 #7
I can't understand what have suggest...plz can u clear me plz
Jul 25 '09 #8
Dormilich
8,658 Expert Mod 8TB
you're simply mixing up the ternary conditional operator and the implode() function call.

essentially, it all is described in the error message (colons have a special meaning in PHP (unless they are part of a string))
Jul 25 '09 #9
Expand|Select|Wrap|Line Numbers
  1.     <?php
  2.     foreach($_POST as $key=>$value)
  3.         { 
  4.         $key.":-".$$key=$value;
  5.         }
  6.     $link=mysql_connect("localhost","root","") or die("Failed Connecting to Database");
  7.     mysql_select_db("query",$link) or die("Failed Connecting To Database");    
  8.  
  9.     $tblname='tbl1';
  10.     $field=array('name','address');    
  11.     $value=array($name,$address);  
  12.  
  13.     echo $success=InsertData($tblname,$field,$data); 
  14.  
  15.     function InsertData($TblName,$Fields,$Values) 
  16.         { 
  17.         global $link; 
  18.         $query="INSERT INTO $TblName(".(is_array($Fields)?implode(",",$Fields):$Fields).")
  19.                 VALUES(".(is_array($Values)? "'".implode("','",$Values).")";
  20.  
  21.                 return ($result=mysql_query($query,$link))?$result:false; 
  22.         } 
  23.  
  24.     ?>
Plz i m frustration from this problem. so plz as you don't mind plz rectify my error & give me errror free code. plz plz
Jul 25 '09 #10
Markus
6,050 Expert 4TB
@luckysanj
First off, 'plz' is spelled 'please'. Adding extra 'z's to the end of this word only makes you look less intelligent. Secondly, please do not beg for code (see point 3). Thirdly, we, as a community, do not just hand out code. After reading your posts, you show little intuition, and I would not be surprised if you got 0 responses from now on.

I apologise for the rant - been a long (but beautiful (weather-wise)) day.

Now, if you'd like to explain what errors you're getting (what is being reported), in clear, concise English, I'm sure we can solve this problem.

Mark (apologies again if I sounded rude before).
Jul 25 '09 #11
Thank You Very much .
Jul 26 '09 #12
ok, I want to Select, Insert, Update & Delete data through one function by passing values through array. which function is constant. & I am inserting data through function variable like $TblName,$Fields,$Values.

The above code line number 18 have one problem. I didn't correct this problem yet. & How can i correct the error.
Jul 26 '09 #13
Canabeez
126 100+
@luckysanj
First with the error, here's the fix I can see:
Expand|Select|Wrap|Line Numbers
  1. function InsertData($TblName,$Fields,$Values) 
  2.    global $link; 
  3.    $query="INSERT INTO `{$TblName}` (`".(is_array($Fields)?implode("`,`",$Fields):$Fields)."`) 
  4.            VALUES (".(is_array($Values)? "'".implode("','",$Values)."')";
  5.  
  6.    return ($result=mysql_query($query,$link))?$result:false; 
  7. }
Now, about mySQL function, there are tons of classes and additions to the regular, built-in mysql functions in PHP, which are probably the best way to work with mysql.

Here's an Example.
Jul 26 '09 #14
Still I have got error .

This is my index.php page:

Expand|Select|Wrap|Line Numbers
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Multiple Data entry with one query</title>
  6. </head>
  7. <body>
  8.  
  9. <form id="form1" name="form1" method="post" action="check.php">
  10.   <table width="200" border="1">
  11.     <tr>
  12.       <td colspan="2">Pesonal Info Table 1 </td>
  13.     </tr>
  14.     <tr>
  15.       <td width="72">Name:</td>
  16.       <td width="112"><input name="name" type="text" id="name" value="Ashok" /></td>
  17.     </tr>
  18.     <tr>
  19.       <td>Address</td>
  20.       <td><input name="address" type="text" id="address" value="Kathmandu" /></td>
  21.     </tr>
  22.     <tr>
  23.       <td><input name="submit1" type="submit" id="submit1" value="Submit" /></td>
  24.       <td><input type="reset" name="Submit2" value="Reset" /></td>
  25.     </tr>
  26.   </table>
  27. </form>
  28. </br>
  29. </br>
  30. </body>
  31. </html>
  32.  
This is my another page: check.php
Expand|Select|Wrap|Line Numbers
  1.     <?php
  2.     foreach($_POST as $key=>$value)
  3.         { 
  4.         $key.":-".$$key=$value;
  5.         }
  6.     $link=mysql_connect("localhost","root","") or die("Failed Connecting to Database");
  7.     mysql_select_db("query",$link) or die("Failed Connecting To Database");    
  8.  
  9.     $tblname='tbl1';
  10.     $field=array('name','address');    
  11.     $value=array($name,$address);  
  12.  
  13.     echo $result=InsertData($tblname,$field,$value);
  14.  
  15.     function InsertData($TblName,$Fields,$Values)  
  16.         {  
  17.         global $link;  
  18.         $query="INSERT INTO `{$TblName}` (`".(is_array($Fields)?implode("`,`",$Fields):$Fields)."`) 
  19.         VALUES (".(is_array($Values)? "'".implode("','",$Values)."')"; 
  20.  
  21.         return ($result=mysql_query($query,$link))?$result:false;  
  22.         } 
  23.     ?>
  24.  
  25.  
  26.  
Error is :Parse error: syntax error, unexpected ';' in D:\xampp\htdocs\my\test\query\check.php on line 20
Jul 26 '09 #15
Canabeez
126 100+
Try this
Expand|Select|Wrap|Line Numbers
  1. $query="INSERT INTO `{$TblName}` (`".(is_array($Fields)?implode("`,`",$Fields):$Fields)."`) 
  2.         VALUES (".(is_array($Values)? "'".implode("','",$Values))."')";
  3.  
Jul 26 '09 #16
Now this error occur on the above php code:
Expand|Select|Wrap|Line Numbers
  1. Parse error: syntax error, unexpected ')' in D:\xampp\htdocs\my\test\query\check.php on line 21
  2.  
Jul 26 '09 #17
On
Expand|Select|Wrap|Line Numbers
  1. $query="INSERT INTO `{$TblName}` (`".(is_array($Fields)?implode("`,`",$Fields):$Fields)."`)  
  2.         VALUES (".(is_array($Values)? "'".implode("','",$Values))."')"; 
Jul 26 '09 #18
Canabeez
126 100+
Sorry, my bad
Expand|Select|Wrap|Line Numbers
  1. $query="INSERT INTO `{$TblName}` (`".(is_array($Fields)?implode("`,`",$Fields):$Fields)."`) VALUES (".(is_array($Values)?"'".implode("','",$Values)."'":$Values).")";
I think now it should work ;)
Jul 26 '09 #19
Ya Sir, It works. Thank you very much for ur cooperation.
Jul 26 '09 #20
Canabeez
126 100+
No problem, Good Luck ;)
Jul 26 '09 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: DPfan | last post by:
What's exactly the meaning of "code reuse" in C++? Why such kind of reuse have more advantages over the counterpart in other language like in C? How is "code reuse" realized in C++? By...
0
by: integragreg | last post by:
I apologize in advance if I am posting to the wrong group, but at least one of my questions is related to Platform Invoke in C#. I am using .NET Framework 1.1, and for improved performance, I...
3
by: Simon | last post by:
Hi all, I'm hoping that some of you clever chaps could offer me some advice on code reuse. You see, whenever I make applications, I typically only find very limited
5
by: apandapion | last post by:
I'm working with csharp and .net for the first time, and I've had a fair amount of luck. I started with the MSDN "Walkthrough : Creating a Distributed Application" tutorial and expanded from...
16
by: sailor.gu | last post by:
Hi all guys, As an embeded programmer with five year C experience, I did read many great books related with design, coding, test,debug,algorithms, compiler, design, os, pm and others. I...
8
by: Edward Diener | last post by:
By reuse, I mean a function in an assembly which is called in another assembly. By a mixed-mode function I mean a function whose signature has one or more CLR types and one or more non-CLR...
19
by: jacob navia | last post by:
There is an interesting discussion running in Slashdot now, about code reuse. The thema of the discussion is here: < quote > Susan Elliot Sim asks: "In the science fiction novel, 'A Deepness...
8
by: WebSnozz | last post by:
I have an application written in C that does a lot of low level stuff. It does a lot of things like casting from void*'s. I want to create a new GUI for it in either C# or MC++, but reuse the...
13
by: JD | last post by:
Hi, My associate has written a copy constructor for a class. Now I need to add an operator = to the class. Is there a way to do it without change her code (copy constructor) at all? Your help...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.