PHP - Undefined index - php

New to PHP, first post on stackoverflow... From the tutorials I've read, I'm 'somewhat' protected from injection, and I know I'm passing my variables correctly from my search form. The issue I'm having is when I attempt to read the results; I receive an "undefined index" error for them and I have no idea why. I've been staring at this and reading for the last day and am about to pull out my hair. Would someone be able to point me in the right direction? and yes, i know, don't use root; this is purely for demo and hosted locally until i have everything smoothed out. Thanks for any help! -Jason
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("%[a-zA-Z0-9_-]%", $_POST["booktext"])){
$searchvalue=$_POST["booktext"];
// create connection
$user="root";
$password="";
$database="bookcat_data";
$host="127.0.0.1:3306";
$searchtype=$_POST["searchtype"];
$con=mysqli_connect($host, $user, $password, $database);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT Book.BookID, Book.Title, Book.AuthorSort, Publisher.Publisher, Book.PublishDate, Book.ISBN FROM ((Book LEFT JOIN Edition ON Book.EditionID = Edition.EditionID) LEFT JOIN PrintedBy ON Book.PrintedByID = PrintedBy.PrintedByID) LEFT JOIN Publisher ON Book.PublisherID = Publisher.PublisherID WHERE " . $searchtype . " LIKE '%" . $searchvalue . "%' ORDER BY Book.Title;";
$result=mysqli_query($con,$sql);
switch($searchtype) {
case "Book.Title":
$header="Book Title";
break;
case "Book.AuthorSort":
$header="Author";
break;
}
echo '<title>' . $header . ' Search for "' . $searchvalue . '"</title>';
echo '<h3 align="center">' . $header . ' Search for "' . $searchvalue . '" - Sorted by Title</h3>';
echo '<table cellpadding="3" cellspacing="2" border="1" id="catalogs" class="center">';
echo '<tr><th>Book Title</th><th>Author</th><th>Publisher</th><th>Publish Date</th><th>ISBN</th>';
while($row=mysqli_fetch_array($result)) {
$BookID=$row['Book.BookID'];
$BookTitle=$row['Book.Title'];
$Author=$row['Book.AuthorSort'];
$Publisher=$row['Publisher.Publisher'];
$PublishDate=$row['Book.PublishDate'];
$ISBN=$row['Book.ISBN'];
echo '<tr>';
echo '<td><a href=\'bookinfo.php?id=$BookID\'>' . $BookTitle . '</td>';
echo '<td>' . $Author . '</td>';
echo '<td>' . $Publisher . '</td>';
echo '<td>' . $PublishDate . '</td>';
echo '<td>' . $ISBN . '</td>';
echo '</tr>';
}
echo '</table>';
mysqli_free_result($result);
mysqli_close($con);
}
}
else{
echo "<p>Please enter an appropriate search</p>";
}
}

SQL queries return the column names without the table prefix. Remove this prefix when accessing your array elements. So $row['BookID'] instead of $row['Book.BookID'].

Related

Using GROUP_CONCAT in while loop to output multiple database entries by same user in one row

Would like to use GROUP_CONCAT in order to retrieve database info (images) from a userid with multiple image entries. These images are in the form of a file path. Would then like to have the images output in a single row per userid.
After extensive research on the matter, I find simple examples of what is needed, but I get lost with the query I currently have in place.
Here is my code as of now:
<table>
<th></th>
<th>Name</th>
<th>Location</th>
<th>High School</th>
<th class="thLargest">Colleges</th>
</table>
<table>
<?php
session_start();
$conn = mysqli_connect("", "", "", "");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT college.id, college.title, GROUP_CONCAT(college.image) AS cImage, users.profileImage, users.fname, users.lname, users.level AS ulevel, users.city, users.state, users.highschool, users.primarysport, usercollege.id, usercollege.collegeid
FROM college, users, usercollege
WHERE usercollege.collegeid = college.id AND usercollege.userid = users.id
ORDER BY usercollege.createdate ASC";
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_assoc($result)) {
if ($row['status'] == null) {
echo "";
}
if ($row['ulevel'] == "A Profile") {
echo '<tr>' .
'<td class="small">' . '<a href="http://www.example.com/aprofile.php?user="'.$row["username"] . '>' . '<img src="'.$row['profileImage'].'" />' . '</a>' . '</td>' .
'<td class="large">' . $row['fname']. ", " . $row['lname'] . '</td>' .
'<td class="large">' . $row['city'] . ", " . $row['state'] . '</td>' .
'<td class="large">' . $row['highschool'] . " (" . $row['primarysport'] . ") " . '</td>' .
'<td class="largest">' .
'<div class="Limage">' . '<img src="images/colleges/'.$cImage.'"/>' . '</div>' .
'</td>' .
'</tr>';
}
}
mysqli_free_result($result);
}
mysqli_close($conn);
?>
</table>
The image portion in question is '<img src="images/colleges/'.$cImage.'"/>' . '</div>'.
A user could have up to 10 entries of college images, so i'd like to display these images side by side, rather than displayed in a different row with the same userid.
In other words, I'd like to group multiple rows of user data from the database in a single row with no duplicate userid in the table.
I've read about exploding the cImage and using foreach as well, but that's where my lack of experience gets me.
SELECT users.profileImage
, users.fname
, users.lname
, users.city
, users.state
, users.highschool
, users.primarysport
, group_concat(college.image) AS cImage
FROM usercollege
INNER JOIN users
ON users.id = usercollege.userid
INNER JOIN college
ON college.id = usercollege.collegeid
GROUP BY users.id
ORDER BY usercollege.createdate ASC
AND
foreach( explode(',', $row['cImage']) as $img )
echo '<div class="Limage">' . '<img src="images/colleges/'.$img.'"/>' . '</div>';

Delete data from mysql database php

Firstly i'm not a developer so bear with me :)
I'm trying to delete a row from a small inventory system we are setting up but its still not allowing me to do anything, this is my current code:
Assigned page:
<?php
$password = 'notTheRealPassword';
$conn = mysql_connect('localhost', 'root', $password);
if(!$conn)
{
die('Error connecting database');
}
mysql_select_db('inventory_system', $conn);
$query= "SELECT * from assigned";
$result=mysql_query($query);
echo "<table border='0' cellpadding='100' class='table-striped'>";
echo "<th>Asset ID</th><th>Asset</th><th>Type</th><th>Manufacturer</th><th>Model</th><th>PC
Name</th><th>Serial Number</th><th>Purchased</th><th>Warranty
End</th><th>OS</th><th>OS
Bit</th><th>CPU</th><th>Memory</th><th>HDD</th><$
while($row = mysql_fetch_array($result))
{
echo '<td>' . $row['asset_id'] . '</td>';
echo '<td>' . $row['asset'] . '</td>';
echo '<td>' . $row['type'] . '</td>';
echo '<td>' . $row['manufacturer'] . '</td>';
echo '<td>' . $row['model'] . '</td>';
echo '<td>' . $row['pc_name'] . '</td>';
echo '<td>' . $row['serial_no'] . '</td>';
echo '<td>' . $row['purchased'] . '</td>';
echo '<td>' . $row['warranty_end'] . '</td>';
echo '<td>' . $row['os'] . '</td>';
echo '<td>' . $row['os_bit'] . '</td>';
echo '<td>' . $row['cpu'] . '</td>';
echo '<td>' . $row['memory'] . '</td>';
echo '<td>' . $row['hdd'] . '</td>';
echo '<td>' . $row['plant'] . '</td>';
echo '<td>' . $row['location'] . '</td>';
echo '<td>' . $row['username'] . '</td>';
echo "<td>Delete</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
Delete page:
<?php
$password = 'notTheRealPassword';
$conn = mysql_connect('localhost', 'root', $password);
if(!$conn)
{
die('Error connecting database');
}
mysql_select_db('inventory_system', $conn);
$id = (int)$_GET['asset_id'];
mysqli_query($conn,"DELETE FROM assigned WHERE asset_id='".$id."'");
mysqli_close($conn);
header("Location: assigned1.php");
?>
I'm guessing it will be something simple.
Cheers,
There are a few things wrong here:
Your GET variable, the one you put in the link, is id, not asset_id
You should not use GET to modify things in your database; if your browser or a plugin decides to pre-fetch links, your database will be wiped out.
You can't mix mysql apis, use either mysqli or mysql (although not the latter...).
The mysql_* functions are deprecated, you should use PDO or mysqli in combination with prepared statements.
When you echo out lots of html, it is easier to just close the php section and then open it again when you need it; now you have php tags inside the echoed texts. The php / strings / html are not separated correctly.

How to display data for a certain period of time (day / week / month) from Mysql table in html table (php)

I use this code to display data from MySQL table in html, but I need the ability to create html tables that will display records added in the last day / week / month.
Here is what I have so far:
<?php
$db_host = 'localhost';
$db_name = 'DB';
$db_username = 'NAME';
$db_password = 'PASS';
$db_table_to_show = 'TABLE';
$connect_to_db = mysql_connect($db_host, $db_username, $db_password)
or die("Could not connect: " . mysql_error());
mysql_select_db($db_name, $connect_to_db)
or die("Could not select DB: " . mysql_error());
mysql_set_charset("utf8");
$qr_result = mysql_query("select * from " . $db_table_to_show)
or die(mysql_error());
echo '<table id="table">';
echo '<thead>';
echo '<tr>';
echo '<th class="table-fandom">fandom</th>';
echo '<th>author</th>';
echo '<th class="table-name">name</th>';
echo '<th>size</th>';
echo '<th class="table-status">status</th>';
echo '<th>date</th>';
echo '<th>tags</th>';
echo '</tr>';
echo '</thead>';
echo '<tbody>';
while($data = mysql_fetch_array($qr_result)){
echo '<tr>';
echo '<td>' . $data['fandom'] . '</td>';
echo '<td>' . $data['author'] . '</td>';
echo '<td>' . $data['name'] . '<div class="menu" style="display: none;"><br> ' . $data['annotation'] . ' </div></td>';
echo '<td>' . $data['size'] . '</td>';
echo '<td>' . $data['status'] . '</td>';
echo '<td>' . $data['date'] . '</td>';
echo '<td>' . $data['tags'] . '</td>';
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
mysql_close($connect_to_db);
?>
PS Sorry for my english, it's not my native language.
if i got it true you want to show data that added for specific date/time or between date/time ranges.
you should use mysql query to get data that for example last day added. you should change query:
$qr_result = mysql_query("select * from " . $db_table_to_show)
first you should save date/time for each row when it added or updated. after that you can get today date/time by PHP functions and then use it in your query.
an example:
SELECT * FROM [TableName] WHERE `AddedDate` BETWEEN "2012-03-15" AND "2012-03-31";
PHP function to get date :
http://php.net/manual/en/function.getdate.php

Mysqli_fetch_assoc not storing as a session variable

I am trying to store my outputted table from mySQL query into session variables and for use in another page. Here's what I have so far, but I do not get an output:
First page that displays the results of my search:
<?php
session_start();
$personid = ($_POST['personid']) ? $_POST['personid'] : $_GET['personid'];
if (empty($personid)) {
echo 'Please enter some search parameters';
} else {
$sql = "SELECT * FROM persons WHERE 1=1";
if ($personid)
$sql .= " AND personid='" . mysqli_real_escape_string($mysqli,$personid) . "'";
$total_records = mysqli_num_rows(mysqli_query($mysqli,$sql));
$sql .= " ORDER BY surname";
$loop = mysqli_query($mysqli,$sql)
or die ('cannot run the query because: ' . mysqli_error($mysqli));
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>Name</th> <th>Address</th> <th>City</th> <th>Province</th> <th>Postal Code</th> <th>Phone Number</th> <th>Email</th> <th></th></tr>";
while ($record = mysqli_fetch_assoc($loop)) {
echo "<tr>";
/* echo '<td>' . $record['firstname'] . $record['surname'] .'</td>';*/
echo "<td>$record[firstname] $record[surname]</td>";
echo '<td>' . $record['address'] . '</td>';
echo '<td>' . $record['city'] . '</td>';
echo '<td>' . $record['province'] . '</td>';
echo '<td>' . $record['postalcode'] . '</td>';
echo '<td>' . $record['phone'] . '</td>';
echo '<td>' . $record['email'] . '</td>';
echo ("<td>Edit</td>");
echo "</tr>";
}
echo "</table>";
$_SESSION['animals']=$loop;
echo "<center>" . number_format($total_records) . " search results found</center>";
}
?>
Click here to see if sessions work
This then goes to this script:
<?php
session_start();
echo "The results";
while ($record = mysqli_fetch_assoc($_SESSION['animals'])) {
echo "<tr>";
echo "<td>$record[firstname] $record[surname]</td>";
echo '<td>' . $record['address'] . '</td>';
echo '<td>' . $record['city'] . '</td>';
echo '<td>' . $record['province'] . '</td>';
echo '<td>' . $record['postalcode'] . '</td>';
echo '<td>' . $record['phone'] . '</td>';
echo '<td>' . $record['email'] . '</td>';
echo ("<td>Edit</td>");
echo "</tr>";
}
What might the problem be? Thanks in advance.
Session are meant to store primitive data types.
Storing a resulstset into a session is a terrible idea and mostly likely bad for server ressources.
If you really need that data somewhere else in your app just query your database again which is not overly expensive.
I can see the problem that you are trying to store the mysqli resource object to the session.
$loop = mysqli_query($mysqli,$sql)
If you want to store the final html to the session, then create a single variable that holds final html string.
$html = "<table>";
while ($record = mysqli_fetch_assoc($loop)) {
$html .= $record['something'];
// Likewise add other variables to html string.
}
$html . = "</table>";
$_SESSION['animals'] = $html
But if you want the array that holds all the database result then you can do like this
$rows = array();
while ($record = mysqli_fetch_assoc($loop)) {
$rows[] = $record;
}
$_SESSION['animals'] = $rows;
Now you use this session value in another pages and iterate and create html.
Just as other website with session variables, using isset will make the script run smoothly
if (!isset($_SESSION['basket'])){
$_SESSION['basket'] = array();
}
Pascal
multiskillz

Filtering records from database table to be view and update

I'm currently trying to pull out records from database and display it on my php form for users to update it. In my database table, there's a column named stage. Under stage, there are foundation, intermediate and advance. Here's an example of it:
Valid XHTML http://img259.imageshack.us/img259/2461/databasei.png.
Valid XHTML http://imageshack.us/photo/my-images/849/profileint.png/.
So when i press the foundation button in my php form(2nd picture), only records where theirs stage are foundation, will be shown on the list(together with their name, contact number, email and student ID)
Is there any way that i can do that
Are you looking for something like this?
<?php
$stage = $_GET['stage'];
$sql = 'SELECT * FROM {$tablename} WHERE stage=:stage';
$db = new PDO('mysql:host=localhost;dbname=yourdbname', $user, $pass);
try {
$statement = $db->prepare($sql);
$statement->execute(array(':stage', db->quote($stage)));
foreach($statement->fetchAll() as $row) {
// Do things here.
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
<?php
include('connect-db2.php');
// get results from database
$result = mysql_query("SELECT * FROM players2 WHERE stage = 'foundation'")
or die(mysql_error());
echo "<table border='1' cellpadding='10'>";
echo "<tr> <th>S/N</th> <th>Student_ID</th> <th>Name</th> <th>Contacts No.</th> <th>Email</th><th>Stage</th></tr>";
while($row = mysql_fetch_array( $result )) {
// echo out the contents of each row into a table
echo "<tr>";
echo '<td>' . $row['id'] . '</td>';
echo '<td>' . $row['student_id'] . '</td>';
echo '<td>' . $row['name'] . '</td>';
echo '<td>' . $row['contact_no'] . '</td>';
echo '<td>' . $row['email'] . '</td>';
echo '<td>' . $row['stage'] . '</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
?>

Categories