Warning: Illegal string offset error - php

I'm trying to create a simple search engine in php, in which if the user enters a keyword they can search by event name or location. Then the results to be displayed in date order. Most of the has been taken from another site, but I am trying to convert it.
Can someone explain the error below to a newbie, in simple terms and how to correct it?
/home/ubuntu/workspace/test/test.php:49: array(5) { 'eventID' => string(1) "1" 'eventName' => string(8) "Exciting" 'eventLocation' => string(7) "Stadium" 'commencing' => string(10) "2017-04-01" 'expires' => string(10) "2017-04-30" } Warning: Illegal string offset 'eventName' in /home/ubuntu/workspace/test/test.php on line 50 Call Stack: 0.0003 238624 1. {main}() /home/ubuntu/workspace/test/test.php:0 1
<?php
session_start();
//include files
include 'header/header.php';
include 'nav/navigation.php';
include 'init.php';
$expires = strtotime($_POST["expires"]);
$expires = date('Y-m-d', $expires);
$events = "";
$find = $_POST['find'];
$field = $_POST['field'];
$searching = true;
if(isset($_POST["submit"])) {
if(!empty($_POST["events"])) {
$searching = false;
}
//This is only displayed if the user submitted the form
if($searching == true)
{
echo "<h2>Results</h2><p>";
//If the user did not enter a search term, they receive an error
if ($find == "")
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to the database
//$result = mysqli_query($connection,$query) or exit ("Error in query:
$query. ".mysqli_error($connection));
// We preform a bit of filtering
$find = strtoupper($find);
$find = strip_tags($find);
$find = trim ($find);
//Now we search for our search term, in the field the user specified
$mysqli = new mysqli('localhost', 'root', '', 'c3470438');
$query = "SELECT * FROM events WHERE upper(eventLocation)
LIKE'%STADIUM%'";
$result = $mysqli->query($query);
//Temporarily echo $query for debugging purposes
//echo "$query";
//exit;
//And display the results
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "<br>";
foreach($row as $item) {
var_dump($row);
echo $item['eventName'];
exit();
}
exit;
//This counts the number or results. If there aren't any, it gives an
explanation
$anymatches=mysql_num_rows($data);
if ($anymatches == 0) {
echo "Sorry, but we can not find an entry to match your query<br>
<br>";
}
//And reminds the user what they searched for
echo "<b>Searched For:</b> " .$find;
}
}
?>
<fieldset>
<legend><h2>Events</h2></legend>
<form name="search" method="post" action="<?=$PHP_SELF?>">
<tr> <th> <td>
<fieldset>
<legend>Find all events</legend>
<input type="radio" name="events" <?php if (isset($events) &&
$events=="all") echo "checked";?>value="all"> Display all events
</fieldset>
<fieldset>
<legend>Find events by date</legend>
<input type="date" name="date" min="<?php echo date("Y-m-d");?>"
max="2025-01-01" value="<?php echo date("Y-m-d");?>">
</fieldset>
<fieldset>
<legend>Find events by keywords</legend>
<input type="hidden" placeholder='Search by keyword'name="searching"
value="yes" />
Search for: <input type="text" name="find" /> in
<Select NAME="field">
<Option VALUE="eventName">Event Name</option>
<Option VALUE="eventLocation">Event Location</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="submit" value="submit" />
</form>
</fieldset>
<button name="submit" value="submit" type="submit" class="button
expanded">Submit </button>
<button type="reset" value="Clear"class="button expanded">
Clear</button>
</fieldset>
</select> </td></tr>
<?php
//include files
include 'footer/footer.php';
?>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script>
</script>
</body>

Well $result->fetch_array(MYSQLI_ASSOC) returns a single row, but you are using it as if it returns all rows. So your foreach is iterating each field in the row, not each row and therefore you're trying to access an array key of a string.
Use a while like so:
while($row = $result->fetch_array(MYSQLI_ASSOC)){
echo $row['eventName'];
}
Also, you're using mysql_num_rows which is not part of mysqli. Instead use $result->num_rows.

Related

Search multiple Criteria - And/or search in PHP

Not sure what I am doing wrong here. I would like to create a search that allows the user to do an and or search.
However when I use the below code, if I type in Brown as Colour1 it will return all results, same as post code.
The goal is to allow the user to search multiple fields to return a match. So Colour1 and Postcode
<html>
<head>
<title> Logo Search</title>
<style type="text/css">
table {
background-color: #FCF;
}
th {
width: 250px;
text-align: left;
}
</style>
</head>
<body>
<h1> National Logo Search</h1>
<form method="post" action="singlesearch2.php">
<input type="hidden" name="submitted" value="true"/>
<label>Colour 1: <input type="text" name="criteria" /></label>
<label>Colour 2: <input type="text" name="criteria2" /></label>
<label>PostCode: <input type="text" name="criteria3" /></label>
<label>Suburb: <input type="text" name="criteria4" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%')
or
('Colour2' like '%$criteria2%')
or
('PostCode' = '%$criteria3%')
or
('Suburb' like '%$criteria4%')
LIMIT 0,5";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
echo "<table>";
echo "<tr> <th>School</th> <th>State</th> <th>Suburb</th> <th>PostCode</th> <th>Logo</th> <th>Uniform</th></tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo "<tr><td>";
echo $row['School'];
echo "</td><td>";
echo $row['State'];
echo "</td><td>";
echo $row['Suburb'];
echo "</td><td>";
echo $row['PostCode'];
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Logo']);
echo "\" /></td></td>";
echo "</td><td><img src=\"data:image/jpeg;base64,";
echo base64_encode($row['Uniform']);
echo "\" /></td></td>";
}
echo "</table>";
}// end of main if statment
?>
</body>
</html>
I can get it to work correctly when I use a dropdown list to select the criteria however I would like them to have multiple options to filter results.
<form method="post" action="multisearch.php">
<input type="hidden" name="submitted" value="true"/>
<label>Search Category:
<select name="category">
<option value="Colour1">Main Colour</option>
<option value="Colour2">Secondary Colour</option>
<option value="PostCode">Post Code</option>
</select>
<label>Search Criteria: <input type="text" name="criteria" /></label>
<input type="submit" />
</form>
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
echo "connected " ;
$category = $_POST['category'];
$criteria = $_POST['criteria'];
$query = "SELECT * FROM `Mainlist` WHERE $category LIKE '%$criteria%'";
$result = mysqli_query($dbcon, $query) or die(' but there was an error getting data');
In general you run your query with AND condition because it has criteria and you have it means that you have to show value by matching each criteria with receptive column. but it also depends on users or client how they want to show their field.
In short it doesn't have any rule how to show.
Played around with it for a bit and found the answer. I needed to define the criteria. see below code
<?php
if (isset($_POST['submitted'])) {
// connect to the database
include('connect.php');
//echo "connected " ;
$criteria = $_POST['criteria'];
$criteria2 = $_POST['criteria2'];
$criteria3 = $_POST['criteria3'];
$criteria4 = $_POST['criteria4'];
$criteria5 = $_POST['criteria5'];
$query = "SELECT * FROM `Mainlist` WHERE (`Colour1`like '%$criteria%') and (`Colour2`like '%$criteria2%')
and (`PostCode`like '%$criteria3%') and (`Suburb`like '%$criteria4%') and (`State`like '%$criteria5%')

Hidden value not posted

I have some Problems with the following code.
The hidden field is not posted to the next page.
I have tried to put it next to the option field, but that creates some different problems like duplicating the dropdownmenue.
can anyone help me please?
<?php
$dbhost = 'localhost';
$dbuser = '-----';
$dbpass = '-----';
$db = '-----';
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($db);
$query = "SELECT * FROM Eintraege"; $result = mysql_query($query);
?>
<form action="deletescript.php" method="post">
<select name="loeschen">
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<option value="<?php echo $line['ID'];?>"><?php echo $line['Titel'];?></option>
<?php
}
?>
</select>
<?php
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<input type="hidden" name="titel" value="<?php echo $line['Titel'];?>" />
<?php
}
?>
Vorname <br /><input type="text" name="name" value="" class="text" /><br /><br />
Name <br /><input type="text" name="vorname" value="" class="text" /><br /><br />
Email <br /><input type="text" name="email" value="" class="text" /><br /><br />
<input type="submit" name="submit" />
</form>
You should at least use mysqli, making sure you have the connection on a secure page like:
// connect.php
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
You have a couple of other problems too.
1) Since mysql_fetch_array() always returns the next row of results, when mysql_fetch_array() is called again in your second while loop, $line is falsey, because there are no more rows to fetch, so the loop does not run. You could reset($line) if you're using fetch like that, but I recommend otherwise.
2) You cannot use the same HTML name attribute twice, unless you add [] to the end of it. Then you can access it as an Array in PHP.
// otherpage.php
<?php
include 'connect.php'; $db = db(); $opts = $hdns = '';
if($q = $db->query('SELECT * FROM Eintraege')){
if($q->num_rows > 0){
while($r = $q->fetch_object()){
$t = $r->Titel;
$opts .= "<option value='$t'>$t</option>";
$hdns .= "<input name='titel[]' type='hidden' value='$t' />";
}
// now you can echo $opts and $hdns where you want
}
else{
$errors[] = 'No result rows were found';
}
$q->free();
}
else{
$errors[] = 'database connection failure';
}
$db->close(); if(isset($errors))die(implode(' & ', $errors));
?>
To get the titel named inputs on the page you are submitting to, it's like:
<?php
if(isset($_POST['titel'])){
// get each one
foreach($_POST['titel'] as $t){
// $t is each one
}
}
?>
Note that getting data to put into hidden inputs then sending it back to the server is generally pointless, since you have access to that information anyways. You'll want to learn AJAX if you want something to go to the database based on Client input.

How to use MYSQL and two different Submit buttons?

I have created a song database (mysql) where a user can enter data into the textfield, select "by artist" or a "by title" radio button and click submit. This all works fine. :)
However, I would like to add another submit button that bypasses the above query and simply lists all of the songs that have been added to the database with a year's time.
I believe that the query I need is:
select * from dt_tb where `dt` >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
but I cannot figure out how to code the PHP to run the query for the songs within the past year.
Here are the two forms I have:
<p>
<form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="Submit" value="Search" />
</form></p>
<form name="form" method="post" action="">
<br />
<input type="submit" name="Newsongs" value="New Releases" />
</form></p>
and here is the current, working php for the 1st query:
<?php
$delimiter = "\t";
$newline = "\n";
$var = #$_GET['q'] ;
$field = #$_GET['field'];
$var = htmlentities($var);
$trimmed = trim($var); //trim whitespace from the stored variable
$search_words = explode(' ', $var);
if ($var != "") {
// rows to return
$limit=100;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database
mysql_connect("DBLocation","DatabaseName","PASSWORD"); //(host, username, password)
//specify database
mysql_select_db("DatabaseName") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "SELECT * FROM Songs where $field like \"%$trimmed%\" order by $field ";
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "<p style=\"color: #00ff00; font-size: 1.2em;\">Results</p>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["title"];
$artist = $row["artist"];
echo "$title";
echo " - ";
echo "$artist";
echo "<br />";
echo $newline;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
}
?>
You can add a hidden field and then check it on submit:
<input type="hidden" name="act" id="act" value="">
Then on your second submit button, use JavaScript to change the value:
<input type="submit" name="Newsongs" value="New Releases" onclick="document.getElementById('act').value = 'list_all'" />
If the value is "list_all", process that, else do your current processing.
if ($_POST['act'] == 'list_all') {
// process second submit button code
} else {
// all your current code
}
You'll want to check if the NewSongs submit button was on the form submitted, and use that in an if statement to do the query or not.
<?php
if (!isset($_POST['NewSongs'])){
//do the search
} else {
//don't do the search
}
?>
You could use 2 submit button inside a form :
<p><form name="form" method="get" action="">
Search for: <input type="text" name="q" />
<input type="radio" name="field" value="title" <?=$checkTitle?> checked> Title
<input type="radio" name="field" value="artist" <?=$checkArtist?> > Artist
<input type="submit" name="submit" value="Search" />
<input type="submit" name="submit" value="New" />
</form>
</p>
<?php
if(isset($_GET['submit']) && $_GET['submit'] == 'Search'){
// do search
}
if(isset($_GET['submit']) && $_GET['submit'] == 'New'){
// do second search
}
?>

Check a check box if it's value is in DB. PHP

I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.

PHP IF ELSE - If seems to be ignored?

i'm a bit of PHP noob, so sorry if this is a daft question, but I just can't figure this out by myself so any help would be greatly appreciated!
I am trying to create a modify page for an events web application. It seems to be working except when I try to validate the final if/else statement.
This statement returns the value of $row[0] and checks if its == NULL. If NULL, it should return an echo 'this event does not exist' to the user, if there is a value, it presents the user with a matrix of text boxes that they can change the data in.
Currently it works fine for the else statement when there is data found, but doesnt recognise the original if when there is no data. Coupled with that, the footer at the bottom of the page disappears!
Here is the main body of the code, i have highlighted the problem area. I understand that there is probably a more effective and efficient way of doing it all, but please keep it simple as I'm still learning. Thanks again. Dan
<div class="round">
<div id="main" class="round">
<span class="bold">MODIFY EVENT</span><br /><br />
On this page you can modify or delete the events that are stored on the database.<br />
Be aware that you cannot undo the DELETE function.<br />
<br />
Find Event:<br />
<table>
<form name="form1" id="form1" method="post" action="
<?php echo $_SERVER["PHP_SELF"]; ?>" >
<tr><th>By Date:</td><td><input type="text" name="modifyDate"
id="modifyDate" value="dd/mm/yy" /></td></tr>
<tr><th>By Name:</td><td><input type="text" name="modifyName" id="modifyName"
value="" /></td></tr>
<tr><th>Find All:</th><td><input type="checkbox" name="modifyAll"
id="modifyAll" /><td></tr>
<tr><td></td><td><input type="submit" name="submit" value="Search" /></td></tr>
</form>
</table>
<?PHP
if(!isset($_POST['modify'])){
if(isset($_POST['submit'])){
$moddate = $_POST['modifyDate'];
If($moddate == "dd/mm/yy"){
$date = "";
}
else{
$newDate = str_replace("/",".",$moddate);
$wholeDate = $newDate;
$dateArray = explode('.', $wholeDate);
$date = mktime(0,0,0,$dateArray[1],$dateArray[0],$dateArray[2]);
}
$name = $_POST['modifyName'];
$all = $_POST['modifyAll'];
$host = "localhost";
$user = "user";
$password = "password";
$db = "database";
$con = mysql_connect($host,$user,$password) or die('Could not connect to Server');
$dbc = mysql_select_db($db, $con) or die('Could not connect to Database');
if($all != 'on'){
$q = "SELECT * FROM events WHERE date = '$date' || title = '$name' ";
}
else{
$q = "SELECT * FROM events";
}
$result = mysql_query($q);
$row = mysql_fetch_array($result) or die(mysql_error());
//THIS IS THE PROBLEM HERE!!!!
if($row[0]==NULL){
echo 'This event does not exist';
}
else{
?>
<form name="form1" id="form1" method="post" action="
<?phpecho $_SERVER['PHP_SELF']; ?>" >
<?PHP
$result = mysql_query($q) or die(mysql_error());
while ($row = mysql_fetch_array($result)){
$initialDate = date('d/m/y', $row['date']);
$ID = $row['ID'];
echo '<input type="text" name="inputEmail" id="inputEmail" value="'.$initialDate.'" />';
echo '<input type="checkbox" value=$ID name="toModify[]" style = "visibility: hidden;" /><br /><br />';
}
echo '<input type="submit" name="modify" value="Modify" />
<br /><br />';
}
}
}
else{
//modify database and return echo to user
}
?>
</div>
<div id="clear"></div>
</div>
</div>
</div>
<div id="footer" class="round shadow"></div>
</body>
</html>
mysql_fetch_array($result) returns false if there are no rows, so it's possible that even if there is nothing in the result, it's still returning a false and your if($row[0] == null) is evaluating to false, also.
In other words, you should be doing a more robust test on the return results from your query to catch fringe cases.
As others have mentioned or implied, here are some things you could / should be doing:
test for rows returned, not values in rows
test for existence of variable, not content of variable
check the database for errors returned
Is the field in the table it's pulling $row[0] from set to NOT NULL? If it is, it will never be a null value. Try instead something like (if empty($row[0]))
You could check the number of result rows to see if there are any events:
$result = mysql_query($q);
$numrows = mysql_num_rows ($result);
if($numrows === 0){
...

Categories