<?php
session_start();
$mysqli = new mysqli('localhost', 'root', '', 'crud') or die(mysqli_error($mysqli)); //Izveido savienojumu ar datubāzi
//default values
$id = 0;
$update = false;
$name = '';
$age = '';
$mobile = '';
$location = '';
if (isset($_POST['save'])){ //pārbauda vai ir nospiesta save poga
$name = $_POST['name'];
$age = $_POST['age'];
$mobile = $_POST['mobile'];
$location = $_POST['location'];
$mysqli->query("INSERT INTO data (name, age, mobile, location) VALUES('$name', '$age', '$mobile', '$location')") or //ievada datus datubāzē
die($mysqli->error);
$_SESSION['message'] = "Record has been saved!"; //iestata sesijas ziņojumu, ja dati tiek saglabāti
$_SESSION['msg_type'] = "success";
header('location: crud.php'); //novirza atpakaļ uz crud.php
}
if(isset($_GET['delete'])){ //pārbauda vai ir nospiesta delete poga
$id = $_GET['delete'];
$mysqli->query("DELETE FROM data WHERE id=$id") or die($mysqli->error()); //izdzēš datus no datubāzes
$_SESSION['message'] = "Record has been deleted!"; //iestata sesijas ziņojumu, ja dati tiek izdzēsti
$_SESSION['msg_type'] = "danger";
header('location: crud.php'); //novirza atpakaļ uz crud.php
}
if(isset($_GET['edit'])){ //pārbauda vai ir nospiesta edit poga
$id = $_GET['edit'];
$update = true;
$result = $mysqli->query("SELECT * FROM data WHERE id=$id") or die($mysqli->error()); //izvēlās datus no datubāzēs
if(count($result)==1){ //ja atrod ierakstu datubāzē
$row = $result->fetch_array(); //atgriež datus no ieraksta
$name = $row['name'];
$age = $row['age'];
$mobile = $row['mobile'];
$location = $row['location'];
}
}
if(isset($_POST['update'])){ //pārbauda vai ir nospiesta update poga
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$mobile = $_POST['mobile'];
$location = $_POST['location'];
$mysqli->query("UPDATE data SET name='$name', age='$age', mobile='$mobile', location='$location' WHERE id=$id") or //atjauno vecos datus uz jaunajiem ievadītajiem datiem
die($mysqli->error);
$_SESSION['message'] = "Record has been updated!"; //iestata sesijas ziņojumu, ja dati tiek atjaunotie
$_SESSION['msg_type'] = "warning";
header('location: crud.php'); //novirza atpakaļ uz crud.php
}
?>
It’s telling me that Parameter must be an array or an object that implements Countable in process.php on line 45, theres a problem with “if(count($result)==1)”, and I can’t find the problem for some reason, probably cos i’m a beginner. Anyway this is a CRUD – Create, Read, Update, Delete – and the Update/Edit function is not working so I’m stuck
2
Answers
mysqli_query
won’t return anything countable, but it’s not necessary to count just to see if you have a result or not. Since you’re selecting by id, you’ll only be able to get a maximum of one row from the query, assuming id is unique.So you can just check that the query executed successfully and then try to get a row from it.
If the query failed,
$result
will befalse
, and if it was successful but didn’t return anything, then$row
will benull
.