Jump to content
Larry Ullman's Book Forums

Recommended Posts

Hi everyone,

Please refer to the following code:

 

<?php # Script 9.2 - delete_user.php

//This page is for deleting a user from the DB
//Accessed through view_user.php

$page_title = 'Delete a user';

include ('includes/header.html');

echo '<h1>Delete a user</h1>';

// Check for a valid user ID, through GET or POST

if ( (isset($_GET['id']) ) && (is_numeric($_GET['id']) ) ) //This checks that the id is appended to the url from view_users.php
{
$id = $_GET['id'];
}
elseif ( (isset($_POST['id'])) && (is_numeric($_POST['id'])) ) //This checks that the id has come from the hidden field in the submitted form
{
$id = $_POST['id'];
}
else
{
//There is no valid id at all and therefore kill the script here
echo '<p class="error">Oops, what are you doing here?</p>';

include ('includes/footer.html');

exit();
}

require_once ('../mysqli_connect.php');

//Check that the form has been submitted.

if (isset($_POST['submitted'])) //Has the form been submitted or just loaded?
{ 
//First check that the user clicked on the yes button on the form
if ($_POST['sure'] == 'Yes')
{
	//Make the query to delete the user
	$q = "DELETE FROM users
		WHERE user_id = $id
		LIMIT 1";

	$r = @mysqli_query($dbc, $q);

	if (mysqli_affected_rows($dbc) == 1) //Checking that the query ran OK
	{
		//Print the success message
		echo '<p>The user has been deleted.</p>';
	}
	else
	{
		//Error message if the query didn't run OK
		echo '<p>The user could not be deleted at the moment because of a system error</p>';

		echo '<p>' . mysqli_error($dbc) . '<br />Query:' . $q . '</p>';
	}
}
else //The user did not click on the yes button on the form
{
	echo '<p>If you want to delete' . $row[0] . 'you need to click on the yes button</p>';
}
}
else //The form has not been submitted yet so load the form
{
//First retrieve the users info. from the DB
$q = "SELECT CONCAT (last_name, ' , ', first_name) FROM users
	WHERE user_id = $id";

$r = @mysqli_query($dbc, $q);

if (mysqli_num_rows($r) == 1) //Check that the query returned a user
{
	$row = mysqli_fetch_array ($r, MYSQLI_NUM);

	//The form for deleting a user

	echo '

	<form action="delete_user.php" method="post">

			<h3>Name: ' . $row[0] . '</h3>

			<p>Are you sure that you want to delete this user?<br />

			<input name="sure" type="radio" value="Yes"> Yes
			<input name="sure" type="radio" value="No" checked> No 
			</p>

			<p><input name="submit" type="submit" value="Submit"></p>

			<input name="submitted" type="hidden" value="TRUE">

			<input name="id" type="hidden" value="' . $id . '">

	</form>';
}
else
{
	//There were no rows or more than 1 row returned by the SELECT query
	echo '<p class="error">Oops, you shouldn\'t be here</p>';
}

}

mysqli_close($dbc);

include ('includes/footer.html');

?>

 

The code works fine, as per Larry's example, but I tried to be smart. Within the following line, which comes up if the user does not confirm the deletion, I tried to insert the users name by using $row[0]. My thinking was that $row[0] has already been populated with the users name when the form loaded. Therefore all I'm doing is referring to the same variable in order to make the sentence read better. The error tells me that it's an undefined variable.

 

echo '<p>If you want to delete' . $row[0] . 'you need to click on the yes button</p>';

 

What am I doing wrong?

 

Cheers

Paul

Link to comment
Share on other sites

What you need to understand is that we have different types of variables.

 

- Local variables

- Instance variables

- Reference variables

 

You $row[0] is a local variable. This is because it's declared inside the while loop. At the end, it dies.

 

What this mean is that the variable does not exist after the while loop. It has no value, and the variable name is gone.

 

$counter = 0; // available also after loops

for ($i=0; $i<5; i++) {

   // $i is a local variable. It's value is available here, but not outside

   echo $i++;  // add one as long as $i is less than 5 (5 times)
   $counter++; // add one as long as $i is less than 5 (5 times)
}

echo $counter; // prints 5
echo $i; // this is another VARIABLE $i. not the same as in the for-loop

$row = mysqli_fetch_array ($r, MYSQLI_NUM) {
   $row[0];    // Working 
}

echo $row[0]; // Not working anymore

 

mysqli_fetch_array is a function. With MYSQLI_NUM as a parameter, this line give meaning to $row[0]. Things in brackets (or what they are called) is arrays. (tables of data). $row[0] is therefor now the DATA of row 0 in the array that holds your database data.

 

Outside $row = mysqli_fetch_array() { } your look at $row[0] as an empty array you are trying to get data from, but that data is long gone. :)

  • Upvote 1
Link to comment
Share on other sites

Hi Antonio,

So, in order to get it to work I would have to run a SELECT query outside of the 'if' and then I could assign that to a variable and use that in some text, i.e.

 

$q = "SELECT CONCAT (first_name, last_name) FROM users
	WHERE user_id = 22;

$r = @mysqli_query($dbc, $q);

echo '<p>This users name is' . $r . '!'</p>';

 

Would that work?

Link to comment
Share on other sites

Hi Antonio,

So, in order to get it to work I would have to run a SELECT query outside of the 'if' and then I could assign that to a variable and use that in some text, i.e.

 

Yes. :)

 

$q = "SELECT CONCAT (first_name, last_name) FROM users WHERE user_id = 22";

$r = @mysqli_query($dbc, $q);

echo '<p>This users name is' . $r . '!'</p>';

Would that work?

 

Almost. There are steps you need to go through to get data from a database.

 

1. Connect to the database (This is the variabel $dbc)

2. Write a query. The variabel of your query is $q.

3. Execute the query.

Almost there... (This is were you stop.

4. Get the info into an array so we can read and display it.

 

You do this with mysqli_fetch_array().

 

I have switched names on your variables to better understand how they work.

 

// This is query
$query = "SELECT CONCAT (first_name, last_name) FROM users WHERE user_id = 22";

// The result of mysqli_query()
$result = @mysqli_query($connection, $query);

// WHILE there is MORE ROWS from mysqli_fetch_array() - Do the below
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    echo '<p>This users name is' . $row["name"] . '!'</p>';
}

// We have displayed all rows

mysqli_fetch_array() can be written with these "parameters". (Values put between the functions ( ... )

mysqli_fetch_array($r, MYSQLI_ASSOC);

mysqli_fetch_array($r, MYSQLI_NUM);

mysqli_fetch_array($r, MYSQLI_BOTH);

 

The difference is how you ask from the row from $row.

 

Assoc let you use THE NAMES of your database table rows ($row["firstname"] . $row["lastname"]),

NUM is the number in the array (Counting from zero) ($row[0] . $row[1])

BOTH means you can mix as you wish.

 

$row["firstname"] . $row["lastname"]

AND

$row[0] . $row[1]

Is the same info :) (If firstname is the first row of the tab, and lastname second.)

  • Upvote 1
Link to comment
Share on other sites

Antonio, big thanks for your help. Just to clear something up, though, PHP does not have block level scope, which is to say that the while loop and such does not create an area of variable scope. The reason that $row has no value after the while loop is that the loop will attempt to fetch records into $row until it can't. At that point the loop is exited, but $row now has no value because it was just assigned no value (thereby breaking the condition of the loop).

 

But thanks again for helping out!

Link to comment
Share on other sites

Antonio,

So I need to use mysqli_fetch_array in order to use the results from a DB query. So $result (in your code below) contains the results of the query but are not accessible. Beginners question, but why does there need to be the extra step. Is it in case the query returns more than one row?

 

Also in your code below where does "name" come from in the echo line. Should it read "$row["firstname"] . $row["lastname"]"

 

Cheers

Paul

Link to comment
Share on other sites

Just to clear something up, though, PHP does not have block level scope, which is to say that the while loop and such does not create an area of variable scope. (...)

 

You still teach me things, Larry. I'm also doing a lot of Java at the moment, so I thought the two worked the same way.

 

Paul. You should learn to read the PHP Manual. Look up mysqli_query() in there, and you see this "Return value". This is really important for understanding what to do with the code. It says that mysqli_query returns an RESULT OBJECT if the query is successfull, and FALSE if the query is not working. This gives you direction for what to do next. This means what you get from mysqli_query is not data, but a data object. That is a difference.

 

Result object:

I don't know if you have heard of objects, but that is not important. The thing is, you need to look at it as a bag or something. You need to tell this object what data to give you, or it makes no sense for PHP. This is the reason we use mysqli_fetch_array. We fetch the result object to an array, and that allows us to point at the object which data to give us from the bag.

 

Return false on $result

You can also see return "False" on failure. This allows us to check if the query is right, or other things.

 

Possible use of this knowledge

You could stop PHP from giving you an error message by checking the $result variable. Because it return false on failure, we can check things.

/* This is the same as if ($result != False) and means "If $result is TRUE" */
if ($result) {
  echo "The query is ok. We got a data object. Now we could use mysqli_fetch_array!!!";
} else {
  echo "Sorry. There's something wrong with the query
}

 

mysqli_fetch_array:

Looking at the manual again, it says this about return values: "Returns an array of strings that corresponds to the fetched row or NULL if there are no more rows in resultset." This means it's perfect to use a while-loop to get this data.

 

// We get date in a result object OR get false back from this
$result = mysqli_query($database, $query);

// If $result got a result object, not false...
if ($result) {
/* This means While there ARE data in $result (while $result is NOT NULL) .... make an array of the data for $row  */
  while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
     /* name is the database table row name. If you also have a row called "lastname" in your table, you can get lastnames too! */
     $row["name"];
     // $row["lastname"]; database table-row name
     // $row["cellphone"]; database table-row name
  }
}
// This means the query is wrong, and mysqli_query returned FALSE to $result.  
else {
  echo "Sorry! $result got false from funciton mysqli_query! It's something wrong with the query"; 
}

Also in your code below where does "name" come from in the echo line. Should it read "$row["firstname"] . $row["lastname"]"

 

This is comming from mysqli_fetch_row. You can choose how mysqli_fetch_row is going to display the result with MYSQLI_ASSOC, MYSQLI_NUM or MYSQLI_BOTH. If you choose MYSQLI_ASSOC, it means use the NAME OF YOUR DATABASE TABLE ROWS. If you use MYSQLI_NUM, you use THE POSITION in the array of $row. Arrays start counting from 0, so 0 is DATA FROM THE FIRST ROW of your table. If you use MYSQLI_BOTH, you can use both the names and the number of the arrays position to display the data. :)

 

Hope you understand this. Learn to read the manual. It can be a bit difficult in the beginning, but learn to look at return and such. It's important. :)

  • Upvote 1
Link to comment
Share on other sites

Antonio,

Thanks for all the time you've put into these replies. I take on board what you're saying about the results of a query being an object that I need to tell what to do with.

 

I have started to look at the PHP manual but as a beginner it can get a little daunting! I will stick with it though.

 

Thanks again for your help.

 

Paul

Link to comment
Share on other sites

 Share

×
×
  • Create New...