Jump to content

Recommended Posts

I came here and got my head bitten off. The facts of life in any programming languages are, you CAN NOT call a function supplying 2 aguments when the called function requires 3 arguments. So

$x = MySchoolResults($user, $class);

function MySchoolResults($pdo, $user, $class) {}

Sorry guys but that's a fact. Also web page programming is diffrent to desktop pc programms. Each web page is an individual who knows nothing about any other web page.

Edited by Paul-D
35 minutes ago, Paul-D said:

The way I had it before worked fine.

The old mysql code did not require working with the connection beyond establishing it.  PHP would implicitly use the previously established connection.  Such implicit things are generally considered poor programming because it can complicate more advanced usages (such as multiple connections).

As such, the newer API's do not use the practice, and require you to explicitly use a specific connection in some way or another.  With PDO that means you need to use the PDO object created when connecting.

38 minutes ago, Paul-D said:

Unless all the other function on this page can have full global access to the static $pdo then this can not work.

Making the variable static within ConnectDB doesn't some how open it up to the world, it only means the value persists across different calls to ConnectDB which lets you avoid having to establish a new connection every time you call the function.  You still have to return that connection, and capture it at the point when you call ConnectDB.  This is a easy find and replace job.  Find: ConnectDB(); Replace with: $pdo = ConnectDB();.  You'll have to update ever where you're doing queries anyway, so you can do this too at the same time.

By using the singleton trick, you do not have to update every calling location of your function, just your calls to ConnectDB.

What are you telling us here that we don't already know?  PHP does allow for an unequal amount of arguments as long as the last ones have a default value in the function's header.

function MySchholResults($pdo, $user, $class) 
{
}
$x = MySchoolResults($user, $class);

The above would not work of course.  And I assume that you are demonstrating how the new db connection would be implemented.  But the workable way would have to be :

function MySchholResults($user, $class, $pdo) 
{
}
$x = MySchoolResults($user, $class, $pdo);

to make it easier to do all these updates you have ahead of you.

Of course the spelling would have to be corrected.

the points that have been made have INCLUDED the reason why you should do these things. these points have been to make your code - secure (it currently is not), provide a good user experience, simplify (i and others have used a form of the word simple in several of the replies) the code (what you have shown contains a lot of unnecessary and unused code, variables, and queries), reduce resources and speed up the code (making a database connection is one of the most time consuming operations you can do on a page, which is why you should make only one per page), and through having useful error handling and validation logic, help get your code/query(ies) to either work or get them to tell you why they won't.

the reason we are trying to get you to simplify the code is because you MUST go though all this code at least once to update it. if you can eliminate the unnecessary code, variables, and queries, you will have less things that must be updated.

if you really have hundreds of pages of bespoke code like what you have shown so far, it may be a better use of your time learning and using a general-purpose data driven design, so that you can get the computer to do the work for you, rather than you spending hours upon hours writing and trying to maintain code on so many web pages.

I can not do this

$x = MySchoolResults($user, $class, $pdo);

The web page would complain. What is this unknown variable $pdo.

<html><body>include functions.php

$User="Me"; $Class="French";

<?$x = MySchoolResults($User, $Class, $pdo); ?>

</body></html>

 

Edited by Paul-D

Just in case I get another bloody nose. so I corrected it.

I notice you want talk about the elephant in the room here which is web based Programming. In Microsoft .Net a web page dosn't supply the connection.

<html>
<body>
<?
$Me = "James";
$Class = "French";
echo "My results are ". MySchoolResults($Me, $Class, $pdo);
?>
</body>
<html>

 

Edited by Paul-D

I think that local development using xampp is the best route for you, Paul-D.

Alot of php specialists have tried to help you but you must help yourself along the way. Go back over all of the tips and advice that you have received, maybe you will find a way to get your code working.

On 3/2/2023 at 11:07 AM, Paul-D said:

I can't beleive you said that PHP7 is at end of life. I am using a company called easyspace. They sent me an email that they are upgrading to PHP7 in one weeks time. 

Yes it is end of life.  Obviously they are behind because PHP 5.6 (which was the last release in the PHP 5 branch) was end of life over 4 years ago.  There was no PHP 6.

ginerjm: Because I have writen in .NET. THe elephant in the room is that nobody here knows about web based programming. A web page can not supply a connection object. The page with all the functions needds to work this out itself. I was hopping that someonr here could supply a way to use a function without adding a $pdo to the function. Seems that I was wrong.

 

I think that posting this on a PHP forum is probably not the way to go.  I am unfamiliar with .Net and don't even know if it uses PHP.   But PHP is all about web-based programming for sure.  We are trying to help you do something in PHP but apparently you are not dealing with PHP.   No wonder things are so confusing - for you and us.

okay ginerjm: solve this then. Nobody here can sort this out. The only way is the way I did it before. Each function makes it's own call.

<html>
<body>
<?
$Me = "James";
$Class = "French";
echo "My results are ". MySchoolResults($Me, $Class, $pdo);
?>
</body>
<html>

 

Edited by Paul-D

What am I supposed to "sort out"? You are writing some html which includes a bit of PHP code (I suggest NOT using short php tags) (and also not mixed-case PHP vars) which will output something that is derived by a PHP function that apparently uses a db to provide data which is then returned to be displayed.

So what is wrong with this?  Looks good to me!

one if you is telling me to not use mdy when it is needed in the database. one of you is changing $conn to $pdo. another is chaging userkey to password. One did tell me to use $pdo = connectDB which does work. Another tells me to add $pdo to the function which dosn't work.

 

Nobody want's to stick with the code I supplied in to you. You want to answere using your own variable names.

Edited by Paul-D
6 minutes ago, Paul-D said:

You want to answere using your own variable names

Given you've been told that

On 3/5/2023 at 3:03 AM, kicken said:

You can use whatever variable name you want, so long as you are consistent about it.

I fail to see how that's a problem. 

This isn't a "fix my code for me" service, it's a help forum.  You're expected to have some basic critical thinking skills and put in some effort of understanding.  You should be able to deduce that one persons $conn is another persons $pdo, just change the names as appropriate.  Same with any other variables.  Everyone has their own conventions and preferences as to what to name thing.

8 minutes ago, Paul-D said:

One did tell me to use $pdo = connectDB which does work.

So why are you still complaining / whinging about variables if this works?  You're just dragging this whole thing out and causing even more confusion about what problems you may or may not have.

Actually the first block of code you provided was addressed and you then showed us how you altered it.  That was good except it had some errors which were then resolved - or so we thought.  

Changing a var form $conn to $pdo was simply a choice someone offered to make it clearer what was done.  You can stick with $conn.   Use of $pdo is more meaningful since the var represents a 'pdo connection'.  

The change of a var name from one thing to another I didn't catch but so what - change it back.

Adding a result var to the call to connectDB function was a necessary thing because otherwise the connection that the function made wasn't available outside of the function.

And the addition of the pdo connection var to the functions parms was necessary to pass the handle to that function since you were told that it was undefined.

 

All important things that were necessary.

 

I think that Kicken gave you same information that I was typing for you.  Seems like we agree on all those things.  Hopefully you can step back and work out what we are saying and how you have to think about your coding practices.

I said I was backing away an hour ago.  Now I think I will.

I used MD5 in my database. I use UserKey instead off a password as I can have more than 1 word. A sentance even using any cahrtecter $%^&£@!

That is why I used md5. Passord is the same as userkey. I even tested the sql and got one record.

My record is found as UserN = 'a39e9eea66930fe0050d56a28bafab72' and UserKey = '44f1fa64d8974c18bcb9182286d3e2aa'

function LogMeX2($name,$pwd1)
{
	$Name = md5($name);
	$Pwd1 = md5($pwd1);
	$sql = "SELECT User, UserKey FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN  = '$Name'";
	echo $sql; // Returns 1 record Name = 'a39e9eea66930fe0050d56a28bafab72' UserKey is the Password = '44f1fa64d8974c18bcb9182286d3e2aa'
	$pdo = connectDB();
	$stmt = $pdo->prepare($sql);
	$stmt->execute([$Name]);
	// fetch/test if a row was found, i.e. the username was found
	if(!$row = $stmt->fetch())
	{
		// username not found
		return false;
	}
	// username found, test password
	if(!password_verify($Pwd1,$row['UserKey']))
	{
		// passwrod didn't match
		return false;
	}
	// username and password matched, return user id
	return $row['User'];
}

 

Paul, if you are looking for someone to program for you, then you've come to the wrong place. You spend more time posting insullts and antagonizing members than you spend trying to fix your highschool programming. Take a break from the keyboard and focus on your code or get out your checkbook and post in the job offer forum. The php specialists here have tried to help you but your eyes and ears are closed. I agree that this thread should reach its end-of-life soon if you don't stop antagonizing. Try to fix your code and the emphasis is on your, id est, y-o-u-r code.

I have spent half an hour loading my xampp, building a db and coding a basic (do not use in reality) php file to illustrate that the tips provided to you work. I even implemented the misuse of a function and i have no problem logging in with my code. You need to look over your files and track down your errors.

page 1 example with no function.

<?php
  //first we make a password for use in a db sans form input
  //$formPass = "MicroSh1t.N3t";
  //$showHash = password_hash($formPass, PASSWORD_BCRYPT);
  //echo $showHash . '<br>';
  $error = 0;

  switch ($_SERVER['REQUEST_METHOD']) {
      case 'POST':
          if (empty($_POST['password'])) { $error = 'login failed.'; break; }

          $dbhost = '127.0.0.1';
          $dbname = 'usertest';
          $dbusername = 'root';
          $dbpassword = '';
          $attributes = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

          $pdo = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8mb4", $dbusername, $dbpassword, $attributes);
          $query = 'SELECT passphrase, id FROM users WHERE username = :user';
          $stmt = $pdo->prepare($query);
          $stmt->execute(array(':user' => $_POST['username']));
          $field = $stmt->fetch();

          if (password_verify($_POST['password'], $field['passphrase']) === true) {
              session_start();
              $SESSION['user']['id'] = $field['id'];
              $loggedin = 1;
          } else {
              $error = 'login failed.'; break;
          }

      break;
  }
  if (empty($loggedin)) {
      if (!empty($error)) { echo $error . '<br>'; }
      echo  "\r\n";
      echo '    <form autocomplete="off" method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">' . "\r\n";
      echo '      <input type="text" name="username" placeholder="username"><br>' . "\r\n"; // required
      echo '      <input type="password" name="password" placeholder="password"><br>' . "\r\n"; // required
      echo '      <input type="submit" value="Log In">' . "\r\n";
      echo '    </form>' . "\r\n";
      echo "\r\n";
  } else {
      echo 'Paul, when does the back-to-school sale begin?';
  }
?>

page example 2 using a function 0.0 (use a class file instead)

<?php
  //first we make a password for use in a db sans form input
  //$formPass = "MicroSh1t.N3t";
  //$showHash = password_hash($formPass, PASSWORD_BCRYPT);
  //echo $showHash . '<br>';
  $error = 0;

  switch ($_SERVER['REQUEST_METHOD']) {
      case 'POST':
          if (empty($_POST['password'])) { $error = 'login failed.'; break; }

          $dbhost = '127.0.0.1';
          $dbname = 'usertest';
          $dbusername = 'root';
          $dbpassword = '';
          $attributes = array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
          $pdo = new PDO("mysql:host=$dbhost; dbname=$dbname; charset=utf8mb4", $dbusername, $dbpassword, $attributes);

          function Misuse_of_Functions_Exemplified($pdo, $nescient) {
              $query = 'SELECT passphrase, id FROM users WHERE username = :user';
              $stmt = $pdo->prepare($query);
              $stmt->execute(array(':user' => $nescient));
              $paul_ution = $stmt->fetch();
              return $paul_ution;
          }
          $paul_ution = Misuse_of_Functions_Exemplified($pdo, $_POST['username']);
          if (password_verify($_POST['password'], $paul_ution['passphrase']) === true) {
              session_start();
              $SESSION['user']['id'] = $paul_ution['id'];
              $loggedin = 1;
          } else {
              $error = 'login failed.'; break;
          }

      break;
  }
  if (empty($loggedin)) {
      if (!empty($error)) { echo $error . '<br>'; }
      echo  "\r\n";
      echo '    <form autocomplete="off" method="post" enctype="multipart/form-data" accept-charset="ISO-8859-1">' . "\r\n";
      echo '      <input type="text" name="username" placeholder="username"><br>' . "\r\n"; // required
      echo '      <input type="password" name="password" placeholder="password"><br>' . "\r\n"; // required
      echo '      <input type="submit" value="Log In">' . "\r\n";
      echo '    </form>' . "\r\n";
      echo "\r\n";
  } else {
      echo 'Paul, when does the back-to-school sale begin?';
  }
?>

i have successfully logged in using both pages. You are doing something wrong. Go back to work and give it a rest today. The specialists here devote their free time helping others. Please show some respect.

Best of luck to you but the rest is up to you...
 

Guest
This topic is now closed to further replies.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.