473,387 Members | 1,486 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,387 software developers and data experts.

pdo request insert problem

can someone tell me what is problem with this application.
am trying to send a friend request but when i click add as friend link,
nothing is inserted into table friendship_requests and sO the request is not sent.
please i need correction

Expand|Select|Wrap|Line Numbers
  1.  
  2. <?php
  3.  
  4. session_start();
  5. //session_regenerate_id();
  6.  
  7. $db = new PDO (
  8.     'mysql:host=localhost;dbname=test', // dsn
  9.     'root', // username
  10.     '' // password
  11. );
  12. //Login section start
  13.  
  14.  
  15.  
  16.  
  17.  
  18. if (!isset($_SESSION['logged'])) {
  19.  
  20.     if (isset($_POST['username']) && isset($_POST['password'])) {
  21.         $statement = $db->prepare('
  22.             SELECT id FROM site_members
  23.             WHERE username = :username
  24.             AND password = :password
  25.         ');
  26.         $statement->execute(array(
  27.             ':username' => $_POST['username'],
  28.             ':password' => $_POST['password']
  29.         ));
  30. //if ($statement->fetchColumn()) {
  31.  
  32.  
  33.         if ($statement->rowCount()) {
  34.             $row = $statement->fetchColumn();
  35.             $_SESSION["logged"] = $row["id"];
  36.  
  37. //echo $row["id"];
  38.  
  39.  
  40.             header("Location: " . $_SERVER["PHP_SELF"]);
  41.             /* why are you redirecting to self? Just drop-through! */
  42.         } 
  43. }else {
  44.             /* you should probably bomb for failed login here ! */
  45. echo("<form method=\"POST\">
  46.     <input type=\"text\" name=\"username\" value=\"Type username here\">
  47.     <input type=\"text\" name=\"password\" value=\"Type username here\">
  48.     <input type=\"submit\" name=\"submit\">  
  49.     </form>");
  50.         }
  51.     }
  52. else {
  53. //end of login section
  54. if (isset($_GET['add'])) {
  55.         // make sure ID trying to be added exists
  56.         $statement = $db->prepare('
  57.             SELECT id FROM site_members
  58.             WHERE id = :id
  59.         ');
  60.         $statement->execute(array(
  61.             ':id' => $_GET['add']
  62.         ));
  63.         /*
  64.             Not sure I understand this, only add a record if the currently
  65.             logged user has already added a user that exists? Just what
  66.             are you trying to do here?!?
  67.         */
  68.         if ($statement->rowCount()) {
  69.             $leoJon = array(
  70.                 ':sender' => $_SESSION['logged'],
  71.                 ':recipient' => $_GET['add']
  72.             );
  73.             /*
  74.                 I'm pulling count instead of whole records as you don't seem
  75.                  to be using the data for anything!
  76.             */
  77.             $statement = $db->prepare('
  78.                 SELECT * FROM friendship_requests
  79.                 WHERE sender = :sender
  80.                 AND recipient = :recipient
  81.             ');
  82.             $statement->execute($leoJon);
  83.             if ($statement->fetchColumn()) {
  84.                 $statement = $db->prepare('INSERT INTO friendship_requests ( sender, recipient ) VALUES ( :sender, :recipient )');
  85.                                 //$statement = $db->prepare('INSERT INTO friendship_requests SET sender = :sender, recipient = :recipient');
  86.                 $statement->execute($leoJon);
  87.             }
  88.         }
  89.     } // END
  90.  
  91. //Section for exceting friendship requests
  92.  
  93.     if (isset($_GET['accept'])) {
  94.  
  95.         $statement = $db->prepare('
  96.             SELECT * FROM friendship_requests
  97.             WHERE sender = :sender
  98.             AND recipient = :recipient
  99.         ');
  100.         $statement->execute(array(
  101.             ':sender' => $_GET['accept'],
  102.             ':recipient' => $_SESSION['logged']
  103.         ));
  104.  
  105.         if ($statement->fetchColumn()) {
  106.  
  107.  
  108.             $selectRec = $db->prepare('
  109.                 SELECT * FROM site_members  
  110.                 WHERE id = :id                   
  111.             ');
  112.                          $selectRec->execute(array(
  113.                 'id' => $_GET['accept']
  114.             ));
  115.  
  116.  
  117.  
  118.             $_row = $statement->fetchColumn();     
  119.  
  120.                          $friends = unserialize($_row["friends"]);
  121.                         $friends[] = $_SESSION['logged'];
  122.  
  123.             $updateLogin = $db->prepare('
  124.                 UPDATE site_members
  125.                 SET friends = :friends
  126.                 WHERE id = :id
  127.             ');
  128.  
  129.             $updateLogin->execute(array(
  130.                 ':friends' => serialize($friends),
  131.                 ':id' => $_GET['accept']
  132.             ));
  133.  
  134.             $selectRec = $db->prepare('
  135.                 SELECT * FROM site_members  
  136.                 WHERE id = :id
  137.             ');
  138.                          $selectRec->execute(array(
  139.                 ':id' => $_SESSION['logged']
  140.             ));
  141.  
  142.                         $_row = $statement->fetchColumn();
  143.                          $friends = unserialize( $_row["friends"]);
  144.                         $friends[] = $_GET['accept'];
  145.  
  146.             $updateLogin = $db->prepare('
  147.                 UPDATE site_members
  148.                 SET friends = :friends
  149.                 WHERE id = :id
  150.             ');
  151.  
  152.             $updateLogin->execute(array(
  153.                 ':friends' => serialize($friends),
  154.                 ':id' => $_SESSION['logged']
  155.             ));
  156.  
  157.         }
  158.  
  159.         $statement = $db->prepare('
  160.             DELETE FROM friendship_requests
  161.             WHERE sender = :sender
  162.             AND recipient = :recipient
  163.         ');
  164.         $statement->execute(array(
  165.             ':sender' => $_GET['accept'],
  166.             ':recipient' => $_SESSION['logged']
  167.         ));
  168.     } // END
  169.  
  170. //Section for showing friendship requests
  171.  
  172.     $selectData = $db->prepare('
  173.         SELECT * FROM friendship_requests
  174.         WHERE recipient = :recipient
  175.     ');
  176.  
  177.     $selectData->execute(array(
  178.         ':recipient' => $_SESSION['logged']
  179.     ));
  180.     if ($selectData->rowCount()) {
  181.         $selectLogin = $db->prepare('
  182.             SELECT * FROM site_members
  183.             WHERE id = :id
  184.         ');
  185.         while ($row = $selectData->fetch()) {
  186.             $selectLogin->execute(array(
  187.                 ':id' => $row['sender']
  188.             ));
  189.             while ($_row = $selectLogin->fetch()) {
  190.                 // assuming you are echoing out something there.
  191.  
  192.  
  193.             }
  194.         }
  195.     }//END
  196.  
  197. // showing result
  198.  
  199.  
  200.     $selectLogin = $db->prepare('
  201.         SELECT * FROM site_members
  202.         WHERE id != :id
  203.     ');
  204.     $selectLogin->execute(array(
  205.         ':id' => $_SESSION['logged']
  206.     ));
  207.     $userList = '';      //200
  208.     while ($row = $selectLogin->fetch()) {
  209.         $alreadyFriend = false;
  210.         $friends = unserialize($row['friends']);                            
  211.         if (isset($friends[0])) {
  212.  
  213.             foreach ($friends as $recData) {
  214.                 if ($recData == $_SESSION["logged"]) $alreadyFriend = true;
  215.  
  216.             }
  217.         }
  218.  
  219.      echo $row["id"];
  220.  
  221.         $selectData = $db->prepare('
  222.             SELECT * FROM friendship_requests
  223. //SELECT count(*) FROM friendship_requests
  224.             WHERE sender = :sender
  225.             AND recipient = :recipient
  226.         ');
  227.         $selectData->execute(array(
  228.             ':sender' => $_SESSION['logged'],
  229.             ':recipient' => $row['id']
  230.         ));
  231.  
  232. if ($selectData->rowCount()) {    
  233.  
  234.         //if ($selectData->countRows()) {    
  235.             echo " - Friendship requested.";
  236.         } elseif ($alreadyFriend == false) {
  237.              echo " - <a href=\"" . $_SERVER["PHP_SELF"] . "?add=" . $row['id'] . "\">Add as friend</a>";
  238.  
  239.         } else {
  240.                   echo " - Already friends.";
  241.         }
  242.         echo '<br />';
  243.  
  244.  
  245.  
  246.  
  247.  
  248.  
  249. //END
  250. }
  251. ?>
  252.  
May 1 '13 #1
6 1919
Dormilich
8,658 Expert Mod 8TB
can someone tell me what is problem with this application.
I’d say, insufficient error handling. currently you do not know whether your conditions trigger or not. (you would need to add debug statements to find that out).

personally I would set PDO’s error handling as follows:
Expand|Select|Wrap|Line Numbers
  1. $db->setAttribute(PDO::ATTR_ERRMODE; PDO::ERRMODE_EXCEPTION);
/*
Not sure I understand this, only add a record if the currently
logged user has already added a user that exists? Just what
are you trying to do here?!?
*/
as I see it, the creator wanted to test, whether
a) the recipient exists
b) a friendship relation to that recipient already exists

the line of thought as I see it:
- line #68: check if the recipient is valid
- line #83: check if the intended sender-recipient relation exists
- then do the insert command

I believe the approach is due to an insufficient DB layout/normalisation. if the DB is properly designed, just the insert command would suffice since any of the above tested cases would throw an error (a constraint violation).

to explain that a bit more detailed, there are 2 tables concerned: a user table (site_members) and a friendship table (friendship_requests).
the minimum requirement for the user table is
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE site_members
  2. (
  3.   id INTEGER AUTO_INCREMENT, -- the user id
  4.   -- more user-related data
  5.   PRIMARY KEY (id)
  6. )
  7.  
the friendship table is a sole table for member relations (called "friendship"), so you need (at least) 2 fields, each for a member (I am assuming that only members can have friendships)
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE friendship_requests
  2. (
  3.   sender INTEGER, -- to be extended
  4.   recipient INTEGER -- to be extended
  5. -- more request status properties, if necessary
  6. )
  7.  
then we have some constraints:
- both sender and recipient must be a member, i.e. they must exist in the user table => foreign keys
- the combination of sender and recipient must be unique => compound keys
hence we set the constraints
Expand|Select|Wrap|Line Numbers
  1. CREATE TABLE friendship_requests
  2. (
  3.   sender INTEGER,
  4.   recipient INTEGER,
  5. -- more request status properties, if necessary
  6.   PRIMARY KEY (sender, recipient),
  7.   FOREIGN KEY (sender) REFERENCES site_members (id),
  8.   FOREIGN KEY (recipient) REFERENCES site_members (id)
  9. )
  10.  
the SQL to insert a new friendship reques is still the same: INSERT INTO friendship_requests (sender, recipient) VALUES (:sender, :recipient);.

what happens if:
- the sender is invalid: you get a foreign key violation
- the recipient is invalid: you get a foreign key violation
- the friendship request already exists: you get a unique key violation

except for the case that you can befriend yourself (which is a pretty cheap test in PHP), we have made all of the previous tests (the SELECTs) obsolete.
May 2 '13 #2
i think the problem is that when click add as friend button,the sender and recipient id is not inserted via SQL INSERT statement and hence the request is not sent. let value be inserted into table friendship_requests and i think things will be okay.

here is the table and you run the code on your own

Expand|Select|Wrap|Line Numbers
  1.  
  2. CREATE TABLE IF NOT EXISTS `friendship_requests` (
  3.   `id` int(11) NOT NULL AUTO_INCREMENT,
  4.   `sender` int(11) NOT NULL,
  5.   `recipient` int(11) NOT NULL,
  6.   PRIMARY KEY (`id`)
  7. ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  8.  
  9.  
  10. CREATE TABLE IF NOT EXISTS `site_members` (
  11.   `id` int(11) NOT NULL AUTO_INCREMENT,
  12.   `username` varchar(255) NOT NULL,
  13.   `password` varchar(11) NOT NULL,
  14.   `friends` text NOT NULL,
  15.   PRIMARY KEY (`id`)
  16. ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
  17.  
  18.  
  19.  
  20. INSERT INTO `site_members` (`id`, `username`, `password`, `friends`) VALUES (1, 'test', '1234', ''),
  21. (2, 'bob', '1234', ''),
  22. (3, 'chuck', '1234', '');
  23.  
  24.  
  25.  
May 2 '13 #3
i have added this below but it displays no error
$db->setAttribute(PDO::ATTR_ERRMODE; PDO::ERRMODE_EXCEPTION);
May 2 '13 #4
Dormilich
8,658 Expert Mod 8TB
here is the table and you run the code on your own
as I suspected, the tables lack proper constraints. besides that the tables don’t help if there are issues gathering the data beforehand.
May 2 '13 #5
how do i make it worked
May 3 '13 #6
Dormilich
8,658 Expert Mod 8TB
first check, which data are passed and which conditions trigger. if your logic doesn’t get to your insert, you do not insert even if the SQL is correct.
May 3 '13 #7

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

Similar topics

4
by: Caversham | last post by:
I am trying to insert data into the fields id and term of the table key. id is an auto-incrementing field. Each of the following forms fails:- INSERT INTO key (id, term) VALUES (0, 'dog') ...
1
by: Sure | last post by:
Hello All, I want to update a form using the LWP & HTTP method. It was working fine when I am updating the values like this $ua = LWP::UserAgent->new; $url...
5
by: John | last post by:
I have the following line in my ASP code. If UCase(Trim(CStr(oRset("Suburb"))))=UCase(Trim(CStr(Request.QueryString("link")))) then etc etc end if
2
by: Harag | last post by:
Hi All Using: JScript IIS 5 I have a problem in the following code: // The next 4 lines display exactly what was typed in the text boxes. out("<br>Request.Form="+...
2
by: Steve Kuekes | last post by:
I have two sql servers, I have defined each one as a linked server to the other. I can mostly access the servers from one another, but I get the following error on a sql insert. Insert...
2
by: mahsa | last post by:
Hi have have some link like thi http://x.com/Shoppingcart.aspx?pn=ps50210&qty_ps50210=1&pn=excel&qty_excel=1&pn=l4504000&qty_l4504000=1&sku=PS50210&cat=laminate&action=updat now I want to request...
0
by: Peter | last post by:
Hello! I am having a strange problem whith the following scenario: I have a html page whith text box and submit button. The form action is aspnet page ant method is post. We have our intranet...
5
by: Raed Sawalha | last post by:
dear : i have the following problem: string sAttachmentBody; int nCount = 0; int nMaxLineLength = 77; //sAttachmentBody.Length may reaches (560960 chars)
5
by: Brad Baker | last post by:
I'm trying to write a simple asp.net page which updates some data in a SQL database. At the top of the page I have the following code: <%@ Page Language="C#" Debug="true" %> <%@ import...
0
AmirGhaffary
by: AmirGhaffary | last post by:
want to insert user Url into data base I work with ASP.NET and i used this code in Session_Start at Global.asax Dim Ref As String If Not Request.UrlReferrer Is Nothing Then ...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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.