Member 13761429 Ответов: 1

Удалите идентификатор undifind , foreach и неопределенное имя возраст и адрес электронной почты в поля данных


index.php


<?php

include_once("../class/Crud.php");

$crud = новый Crud();

$query = "SELECT * FROM users ORDER BY id DESC ";
$result = $crud->getData($query);
//эхо "
"; print_r($result); exit; 

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Homepage



<a href="add.php">Add New Data</a><br><br>
	
    	        <?php
		
		foreach($result as $key => $res) {
			echo "";
			echo "";
			echo "";
			echo "";
			echo " ";
		}
		
		?>
    <table width="80%" border="0"><tbody><tr>        <td>Name</td>        <td>Age</td>        <td>Email</td>        <td>Update</td>        </tr><tr><td>".$res['name']."</td><td>".$res['age']."</td><td>".$res['email']."</td><td><a href=\"edit.php?id=$res[id]\">Edit |
				  <a href=\"delete.php?id=$res[id]\" onclick=\"return confirm('Are you sure you want to delete?')\">Delete</td></tr></tbody></table>





Crud.php



<?php

include_once '../class/DbConfig.php';

class Crud extends DbConfig {
	public function __construct() {
		parent::__construct();
	}
	
	public function getData($query) {
		$result = $this->connection->query($query);
		
		if($result == false) {
			return false;
		}
		
		$rows = array();
		
		while($row = $result->fetch_assoc()) {
			$rows[] = $row;
		}
		return $rows;
	}
	
	public function execute($query) {
		$result = $this->connection->query($query);
		
		if($result == false) {
			echo "can't execute the command";
			return false;
		} else {
			return true;
		}
	}
	
	public function escape_string($value) {
		return $this->connection->real_escape_string($value);
	}
}

?>


add.php


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add data



<?php

include_once("../class/Crud.php");
include_once("../class/Validation.php");

$crud = new Crud();
$validation = new Validation();

if(isset($_POST['Submit'])) {
	$name = $crud->escape_string($_POST['name']);
	$age = $crud->escape_string($_POST['age']);
	$email = $crud->escape_string($_POST['email']);
	
	$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
	$check_age = $validation->is_age_valid($_POST['age']);
	$check_email = $validation->is_email_valid($_POST['email']);
	
	if($msg != null) {
		echo $msg;
		echo "<br><a>Go back</a>";
	} else if(!$check_age) {
		echo "Please provide proper age.";
	} else if(!$check_email) {
		echo "Please provide proper email.";
	}
	else {
		$result = $crud->execute("INSERT INTO users(name, age, email)VALUES('$name', '$age', '$email')");
		
		echo "<font color="green">Data added successfully.";
		echo "<br><a href="index.php">View result</a>";
	}
}

?>




Validation.php


<?php

class Validation {
	public function check_empty($data, $fields) {
		$msg = null;
		foreach($fields as $value) {
			if(empty($data[$value])) {
				$msg .= "$value field empty <br>";
			}
		}
		return $msg;
	}
	
	public function is_age_valid($age) {
		if(preg_match("/^[0-9]+$/", $age)) {
			return true;
		}
		return false;
	}
	
	public function is_email_valid($email) {
		if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
			return true;
		}
		return false;
	}
}

?>


DbCongig.php


<?php

class DbConfig {
	private $_host = 'localhost';
	private $_username = 'root';
	private $_password = '';
	private $_database = 'test1';
	
	protected $connection;
	
	public function __construct() {
		if(!isset($this->connection)) {
			$this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
			
			if(! $this->connection) {
				echo "can't connect to database";
				exit;
			}
		}
		return $this->connection;
	}
}

?>


add.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Add data



<a href="add.php">Home</a>
<br><br>


<table width="25%" border="0"><tbody><tr><td>Name</td><td></td></tr><tr><td>Age</td><td></td></tr><tr><td>Email</td><td></td></tr><tr><td></td><td></td></tr></tbody></table>





edit.php


<?php

include_once("../class/Crud.php");

$crud = new Crud();

$id = $crud->escape_string($_GET['id']);

$result = $crud->getData("SELECT * FROM users WHERE id=$id");

foreach($result as $res) {
	$name = $res['name'];
	$age = $res['age'];
	$email = $res['email'];
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">


<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit data



<a href="index.php">Home</a>
<br><br>


	
    	        
                
                
        <table border="0"><tbody><tr>        <td>Name</td>        <td></td>        </tr><tr>        <td>Age</td>        <td></td>        </tr><tr>        <td>Email</td>        <td></td>        </tr><tr>        <td></td>        <td></td>        </tr>	</tbody></table>





editaction.php


<?php

include_once("../class/Crud.php");
include_once("../class/Validation.php");

$crud = new Crud();
$validation = new Validation();

if(isset($_POST['update'])) {
	$id = $crud->escape_string($_POST['id']);
	
	$name = $crud->escape_string($_POST['name']);
	$age = $crud->escape_string($_POST['age']);
	$email = $crud->escape_string($_POST['email']);
	
	$msg = $validation->check_empty($_POST, array('name', 'age', 'email'));
	$check_age = $validation->is_age_valid($_POST['age']);
	$check_email = $validation->is_email_valid($_POST['email']);
	
	if($msg) {
		echo $msg;
		echo "<br><a>Go Back</a>";
	} elseif(! $check_age) {
		echo "Please provide proper age.";
	} elseif(! $check_email) {
		echo "Please provide proper email.";
	} else {
		$result = $crud->execute("UPDATE users SET name='$name', age='$age', email='$email' WHERE id=$id ");
		header("Location:index.php");
	}
}

?>


error:

Notice: Undefined index: id in C:\xampp\htdocs\crud_php\class\edit.php on line 7

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\crud_php\class\edit.php on line 11

inside name field:   <br>Notice:  Undefined variable: name in C:\xampp\htdocs\crud_php\class\edit.php on line 33<br>


inside age field:   <br>Notice:  Undefined variable: age in C:\xampp\htdocs\crud_php\class\edit.php on line 38<br>



inside email field:   <br>Notice:  Undefined variable: email in C:\xampp\htdocs\crud_php\class\edit.php on line 43<br>

What I have tried:

<big>i try every solution but its shows error like this</big>


Notice: Undefined index: id in C:\xampp\htdocs\crud_php\class\edit.php on line 7

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\crud_php\class\edit.php on line 11

inside name field:   <br>Notice:  Undefined variable: name in C:\xampp\htdocs\crud_php\class\edit.php on line 33<br>


inside age field:   <br>Notice:  Undefined variable: age in C:\xampp\htdocs\crud_php\class\edit.php on line 38<br>



inside email field:   <br>Notice:  Undefined variable: email in C:\xampp\htdocs\crud_php\class\edit.php on line 43<br></font>

Kornfeld Eliyahu Peter

Единственный способ решить эти проблемы-изучить основы PHP...

1 Ответов

Рейтинг:
1

ThilinaMD

Таким образом, ошибка четко указана в строке 7. Вы должны использовать значения строк таблицы внутри $res[] используя перевернутые запятые. $res[id] должно измениться как $res['id'] или $res["id"]. Убедитесь, что имена столбцов таблицы и значения $res[] совпадают.


Member 13761429

не решить

Member 13761429

<?php

include_once("../class/Crud.php");

$crud = новый Crud();

$идентификатор = $твар-и GT;escape_string (переменная$_GET['идентификатор']);

$result = $crud->delete($id, 'users');

if($result) {
заголовок("Location: index.php");
}

?>

также ошибка при запуске delete.php его работа, но когда особенно запустить delete,php его показывает ошибку:


Обратите внимание: неопределенный индекс: id in C:\xampp\htdocs\crud_php\class\delete.php на линии 7

ThilinaMD

Вы должны передать значение для идентификатора параметра из поля формы(входной тег) или в качестве параметра url, например delete.php?id=1

ThilinaMD

Это будет полезно, если вы изучите базовый творог на php через любой онлайн-учебник, например tutorialspoint

Member 13761429

я уже сделал это но это не сработало