472,330 Members | 1,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,330 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 3287
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?...
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...
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...
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...
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,...
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...
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...
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...
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...
0
by: tammygombez | last post by:
Hey fellow JavaFX developers, I'm currently working on a project that involves using a ComboBox in JavaFX, and I've run into a bit of an issue....
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: CD Tom | last post by:
This happens in runtime 2013 and 2016. When a report is run and then closed a toolbar shows up and the only way to get it to go away is to right...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
0
by: AndyPSV | last post by:
HOW CAN I CREATE AN AI with an .executable file that would suck all files in the folder and on my computerHOW CAN I CREATE AN AI with an .executable...

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.