/    Sign up×
Community /Pin to ProfileBookmark

Undefined offset 0

Hi,

when I run the following code, it works when I change the id value in the query string that is not in the database table, but it also says:

Notice: Undefined offset: 0 in C:xampphtdocssandboxorganising-pdoindex2.php on line 11

[code=php]require ‘functions.php’;

$conn = connect($config);

if ($conn) {
$id = isset($_GET[‘id’]) ? (int)$_GET[‘id’] : 11;
$row = get_by_id(“SELECT * FROM users WHERE id = :id”,
array(‘id’ => $id),
$conn)[0];
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php if ($row) : ?>
<h1><?= $row[‘username’];?>’s Profile </h1>
<?php else: ?>
<h1>No user</h1>
<?php endif; ?>
</body>
</html>[/code]

why? How can I fix it?

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@bionoidApr 21.2014 — if ($conn) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 11;
$row = get_by_id("SELECT * FROM users WHERE id = :id",
array('id' =&gt; $id),
$conn)[COLOR="#FF0000"][0][/COLOR];
}


Well it appears as if you're accessing the first member of an array [FONT=Courier New]get_by_id[/FONT] is passing back, clearly it is empty if no matches were found in the database. Off the top of my head, this might be a safer way to check the row:

[code=php]require 'functions.php';

$conn = connect($config);

if ($conn) {
$id = isset($_GET['id']) ? (int)$_GET['id'] : 11;
$row = get_by_id("SELECT * FROM users WHERE id = :id",
array('id' => $id),
$conn);
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php if ($row) : ?>
<h1><?= $row[0]['username'];?>'s Profile </h1>
<?php else: ?>
<h1>No user</h1>
<?php endif; ?>
</body>
</html>[/code]


Untested.
Copy linkTweet thisAlerts:
@Imam_GainsauthorApr 21.2014 — thanks, that worked.

PHP if fun but frustrating!
×

Success!

Help @Imam_Gains spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...