assigned $output from search form not printing - php

I trying to create a search form but there is something wrong with the $output .= , can't figure it out. I followed a tutorial and the function is working, but since $output isn't assigned correct, it prints nothing or only the . .
Here is the code:
<?php
$output= "";
if(isset($_POST['fornamn'])) {
$searchq = $_POST['fornamn'];
$resultat = mysqli_query($conn, "SELECT * FROM Garanti_tekniker91 WHERE fornamn LIKE '%searchq%' OR efternamn LIKE '%$searchq%'") OR die(mysqli_error());
$rader = mysqli_num_rows($resultat);
if($rader == 0) {
$output = 'Finns inga resultat för: "' . $searchq . '"';
}
else
{
while ($row = mysqli_fetch_array($resultat)) {
$garantinummer = $row['garantinummer'];
$fornamn = $row['fornamn'];
$efternamn = $row['efternamn'];
$telefon = $row['telefon'];
$output .= '<p>'. $fornamn . '</p>';
}
}
}
else {
header("location: ./");
}
print("$output");
mysqli_close($conn);
?>

First of all, you should prepare your variable:
$searchq = filter_var($_POST['fornamn'], FILTER_SANITIZE_STRING);
next, please use { ... } if you put variables in a quoted string:
$resultat = mysqli_query($conn, "SELECT * FROM Garanti_tekniker91 WHERE fornamn LIKE '%{$searchq}%' OR efternamn LIKE '%{$searchq}%'") OR die(mysqli_error($conn));
and as told the commentator above - you skipped $ in your query.

This code is up on support.mewebbdesign.se if you guys want to test it.
Updated code:
<?php $servername = "entered";
$username = "entered";
$password = "entered";
$dbname = "entered";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Kunde inte koppla upp.: " . $conn->connect_error);
}
else {
echo "Uppkopplad <br/><br/>";
}
?>
<?php
$output= "";
if(isset($_POST['fornamn'])) {
$searchq = filter_var($_POST['fornamn'], FILTER_SANITIZE_STRING);
$resultat = mysqli_query($conn, "SELECT * FROM Garanti_tekniker91 WHERE fornamn LIKE
'%{$searchq}%' OR efternamn LIKE '%{$searchq}%'") OR die(mysqli_error($conn));
$rader = mysqli_num_rows($resultat);
if($rader == 0) {
$output = 'Finns inga resultat för: "' . $searchq . '"';
}
else
{
while ($row = mysqli_fetch_array($resultat)) {
$garantinummer = $row['garantinummer'];
$fornamn = $row['fornamn'];
$efternamn = $row['efternamn'];
$telefon = $row['telefon'];
$output .= '<p>'. $fornamn . '</p>';
}
}
}
else {
header("location: ./");
}
print("$output");
mysqli_close($conn);
?>

Related

PHP Fetch row data from Mysql via ID

I am new to php. I have the following code that auto fetches all the rows and columns from the db. I want to make the script to fetch a particular row using its ID column. for example: www.site.com/view.php?id=22
I am trying to get it work with the $_GET['link']; variable like this:
if (isset($_GET['id'])) {
$result = mysqli_query($connection,"SELECT * FROM $_GET['link']");
} else {
$result = mysqli_query($connection,"SELECT * FROM reservations");
}
But I am unable to get it work.
The complete code is as below:
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
//get results from database
$result = mysqli_query($connection,"SELECT * FROM reservations");
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
?>
Any help would be appreciated..
You can do this
Add
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
and change this
mysqli_query($connection,"SELECT * FROM reservations");
to this
$result = mysqli_query($connection, $query);
In the above code I added a bit of security so that if $_GET['id'] is not a valid integer it will revert to query where it fetches all the data. I added that because you should never put $_GET directly into your query.
Here is a your code I have modified it to your requirements
<?php
$host = "localhost";
$user = "user";
$pass = "Pass1";
$db_name = "test";
//create connection
$connection = mysqli_connect($host, $user, $pass, $db_name);
//test if connection failed
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$query = 'SELECT * FROM reservations';
if (!empty($_GET['id']) and ($id = (int)$_GET['id']))
$query .= " WHERE id = {$id} LIMIT 1";
//get results from database
$result = mysqli_query($connection, $query);
$all_property = array(); //declare an array for saving property
//showing property
echo '<table class="data-table" border="1">
<tr class="data-heading">'; //initialize table tag
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>'; //get field name for header
array_push($all_property, $property->name); //save those to array
}
echo '</tr>'; //end tr tag
//showing all data
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>'; //get items using property value
}
echo '</tr>';
}
echo "</table>";
if(isset($_GET['id'])) {
$id = $_GET['id'];
} else {
$id=NULL;
}
$sql = "SELECT * FROM reservations WHERE id = '".$id."'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) == 1) {
dd($row);
} else {
echo "no records found with this id";
}
Hope this script meets your answer

Can't get data from MySQL

I'm connected to phpmyadmin but I can not get any data from phpmyadmin.
my php version is 7.2.9 , I made everything that I wanted in database but php can't show the data in site ( I'm using localhost ).
here is the code:
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
$query = "SELECT * FORM search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= "OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
mysql_connect("localhost", "root", "");
mysql_select_db('search');
$query = mysqli_query($query);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</h2></a>
$description<br /><br />";
}
}
else{
echo "No results found for \"<b>$key</b>\""; }
//disconnect
mysql_close();
?>
You have a couple of mistakes in your PHP/HTML. I'm gonna sum them up here so you can take a look at them:
<h2><a href='$link'>$title</h2></a>$description<br /><br /> This is wrong HTML. Close your a tag inside the h2.
You are connecting to you database through mysql, but querying through mysqli. Connect to your database with mysqli. Mysql_ family of functions have been removed in PHP 7
You have a typo in your query. you have written FORM instead of FROM.
You are exploding your $_GET variable on spaces. But i doubt if a $_GET variable has any spaces to begin with... Check if this is true.
first of all mysql_connect() is not anymore available after php 5. Instead of using mysql use mysqli_connect(). Please how to make connection and query database using php7 here.
https://www.w3schools.com/php/func_mysqli_fetch_row.asp
If still you have problem. Ask for help in comments.
<?php
$query = "SELECT * FORM search WHERE ";
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= "OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
$conn = mysqli_connect("localhost", "root", "","search");
if(!$conn)die("Connection Error");
$query = mysqli_query($conn,$query);
if(!query)die("query error");
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while ($row = mysqli_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</h2></a>
$description<br /><br />";
}
}
else{
echo "No results found for \"<b>$key</b>\"";
}
You are mixing up mysqli and mysql. I have edited your stuff. Please try. Don't forget to fix the portion marked [missing]
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
foreach ($terms as $each){
$i++;
if($i == 1){
$query .= "keywords LIKE '%$each%' ";
} else{
$query .= " description OR keywords LIKE '%$each%' ";
}
echo $query;
}
//connection
$conn=mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'search');
if($result= mysqli_query($conn, $query)){
$numrows = mysqli_num_rows($result);
}
if($numrows > 0){
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
//echo "<h2><a href='$link'>$title</h2></a>
//$description<br /><br />";
echo '<h2><a href="' . $link . '">' . $title .
'</h2></a>' . $description . '<br /><br />';
}
}
else{
echo "No results found for \"<b>$key</b>\""; }
//disconnect
mysqli_close();
?>
Here's the Full working Example TESTED at my end (Last night I wasn't at my work machine and couldn't test the code.Later I created a small db and Tested it. I had searched with the dummy key 'ram mary albert' in my example
<?php
$key = $_GET['key'];
$terms = explode(" ", $key);
$qu1 = "SELECT * FROM search WHERE ";
$qu2 = "order by id ASC";
$conn=mysqli_connect("localhost", "root", "");
mysqli_select_db($conn, 'search');
for($i=0; $i< count($terms); $i++){
$query = $qu1 . " keywords LIKE '%$terms[$i]%' " . $qu2;
echo( $query . "<br>" );
$resulter= mysqli_query($conn, $query);
while($row = mysqli_fetch_array($resulter)){;
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$EscLink='\'' . $link . '\'';
echo ('<a href="javascript:void(0)" onClick="alert(' .
$EscLink . ')">' . $title . '</a><br>' . $description .
'<br /><br />');
} // Close While
} // Close for
//disconnect
mysqli_close($conn);
?>

Display only 20 characters from content? Display paragraphs?

I have separate question really which I need help. I only want to display say 20 characters from 'content'.
<?php
$output = '';
if(isset($_GET['q']) && $_GET['q'] !== ' ') {
$searchq = $_GET['q'];
$q = mysqli_query($db, "SELECT * FROM article WHERE title LIKE '%$searchq%' OR content LIKE '%$searchq%'") or die(mysqli_error());
$c = mysqli_num_rows($q);
if($c == 0) {
$output = 'No search results for <strong>"' . $searchq . '"</strong>';
} else {
while($row = mysqli_fetch_array($q)) {
$id = $row['id'];
$title = $row ['title'];
$content = $row ['content'];
$output .= '<a href="article.php?id=' .$id. '">
<h3>'.$title.'</h3></a>'.$content.'';
}
}
} else {
header("location: ./");
}
print("$output");
mysqli_close($db);
?>
i will answer your first question:
insert this line after:
$content = $row ['content'];
if(strlen($content)>20) $content=substr ($content,0,19);

PHP Fatal error: Could not queue new timer in Unknown on line 0

I write a simple web application for my compnay that can let user log in to arrange their work time. Besides, user can also view the report of he's or she's attandence that I use ajax to callback from java.jar. (We use java to analyze)I use Xampp to set up the server in virtual machine HyperV and it can run successfully at the begining but after twenty hours or more than one day it won't let anyone to log in.
I open the error.log shows that :
PHP Fatal error: Could not queue new timer in Unknown on line 0
. . . and than:
PHP Warning: mysqli_connect(): (HY000/2002): Unknown Error
I don't understand what can cause that happend and how to solve it.
I alreday know is when I restarted the apache server, it can still be used till that error happened.
My System Enviroment :
win7 64 bit HyperV
xampp Apache/2.4.18, php/7.0.6, mysql/ 5.1
Here is my code:
mysql_start.php
<?php
header("Content-Type:html;charset=utf-8");
$servername = "127.0.0.1";
$username = "root";
$password = "cc1234";
$dbname = "cc_tw000427";
$conn = null;
try {
$conn = new mysqli($servername, $username, $password, $dbname);
} catch (Exception $e) {
$error_message = "Connect Error (" .$conn->connect_errno ." )" . $conn->connect_error;
error_log($error_message, 3, "php_error_log");
header("location:login.php?err=$e");
}
$conn->set_charset("utf-8");
$strDBColLoingAccount = "AccountID";
checklogin.php
session_start();
include_once("mysql_start.php");
$yid = trim(filter_input(INPUT_POST, "yid"));
$passd = trim(filter_input(INPUT_POST,"passd"));
$strSql = "SELECT acc.*, b.String_10_1 FROM basicstoreinfomanageacc_sub acc,basicstoreinfo b
WHERE acc.$strDBColLoingAccount ='$yid' AND acc.String_50_1 = b.String_50_1";
$result = $conn->query($strSql);
$n = $result->num_rows;
if ($n == 0) {
header("Location:../desktop/login.php?err=1");
echo "Error 1";
exit();
}
while ($row = $result->fetch_assoc()) {
$passd_right = $row["AccountPwd"];
$user_id = $row["AccountID"];
$user_name = $row["AccountName"];
$user_dep_id = $row["String_10_1"];
$user_dep = $row['String_50_1'];
}
$result->close();
if (($passd_right == "") || ($passd_right == NULL)){
session_start();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
header("location:newpwd.php");
exit();
}
if ($passd == $passd_right) {
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $user_name;
$_SESSION['loginOK'] = 'yes';
$_SESSION['year_i'] = date('Y',time());
$_SESSION['year_f'] = date('Y',time());
$_SESSION['month_i'] = date('m',time());
$_SESSION['month_f'] = date('m',time());
$_SESSION['day_i'] = date('d',time());
$_SESSION['day_f'] = date('d',time());
$_SESSION['Hour'] = date('Y-m-d G:i:s',strtotime('+6 hour'));
$_SESSION['user_dep_id'] = $user_dep_id;
$_SESSION['user_dep'] = $user_dep;
header("Location:../desktop/Punch.php");
} else {
header("Location:../desktop/login.php?err=1");
}
$conn->close();
?>
Next two *.php files are used to receive the post from the web.
The select.php is used to select the data from mysql than output in html tag.
The save.php is used to save the data post from web.
select.php
<?php
session_start();
include_once '../control/mysql_start.php';
$strYear = $_POST['year'];
$strMonth = $_POST['month'];
$strDay = $_POST['day'];
.
.//some codes
.
$strSql = "SELECT * FROM basicemploymentinfo bei WHERE bei.BelongStore = '". $_SESSION['user_dep']."'".
"AND ((bei.datetime_2 is null AND bei.datetime_3 is null) OR (bei.datetime_2 is null AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 is null)" .
" OR (bei.datetime_2 <= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d') AND bei.datetime_3 >= STR_TO_DATE('" . $strDate . "', '%Y-%m-%d'))) "
."AND bei.Active ='Y'";
$EmpId = array();
$EmpName = array();
if ($result = $conn->query($strSql)) {
while($row = $result->fetch_assoc()) {
array_push($EmpId, $row['String_20_1']);
array_push($EmpName, $row['String_20_2']);
.
.//some codes
.
}
}
$Emp = array_combine($EmpId, $EmpName);
$strSql = " SELECT Distinct date_format(DateTime_1, '%e') as date, AutoCheck
FROM hrotcheck
WHERE date_format(DateTime_1, '%Y-%m-%d') = '$newformat'
AND AutoCheck = 'C'
AND String_20_1 IN ($array_emp_id)";
if ($result = $conn->query($strSql)) {
$n = $result->num_rows;
if ($n > 0) { $checkboxVerify = 'C';}
}
$result->close();
foreach ($Emp as $EId => $EName)
{
.
.//some codes
.
$strSql = "SELECT RegularM_1, RegularM_2, FORMAT(OT_3, 1) as OT_3, TOM, TOTM, Notes, AutoCheck FROM hrotcheck where string_20_1 = '" . $EId . "' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result = $conn->query($strSql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$RegularM_1 = $row['RegularM_1'];
$RegularM_2 = $row['RegularM_2'];
$OT3 = $row['OT_3'];
$tom = $row['TOM'];
$totm = $row['TOTM'];
$notes = $row['Notes'];
}
}
$result->close();
.
.//I did a lot of SQL select and use that to create htmltable
.
$output .= '
<tr data-table="sub">
<td>'.$row['string_20_1'].'</td>
<td>'.$row['string_20_2'].'</td>
.
.//<td>...</td>
.
<td class="'.$condition16.'">'.$notes.'</td>
<td class="'.$condition17.'"></td>
</tr>
';
}
.
.//some codes
.
$strSql01 = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$row['string_20_1']."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$newformat'";
$result01 = $conn->query($strSql01);
if ($result01->num_rows > 0) {
while ($row01 = $result01->fetch_assoc()) {
.
.//some codes
.
}
}
$result01->close();
.
.//some codes
.
$result->close();
$conn->close();
echo $optionUse.'?'.$checkboxVerify.'?'.$output.'?'.$hasCheckDate;
?>
save.php
<?php
session_start();
include_once '../control/mysql_start.php';
$arrayObjs = $_POST;
.
.//some codes
.
$msDanger = '';
foreach($arrayObjs as $array)
{
foreach($array as $row)
{
$UserId = $row['UserId'];
$UserName = $row['UserName'];
.
.//some codes
.
$strSql = "SELECT * FROM manufacturejobschedulingpersonal where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
$result = $conn->query($strSql);
if( $result->num_rows > 0) {
if ($table == 'main') {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1', String_Assist01 ='$assist_1',String_Assist02='$assist_2' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
} else {
$strSql = "Update manufacturejobschedulingpersonal SET String_10_1 ='$String_10_1' where string_20_1 = '".
$UserId."' AND"." date_format(DateTime_1,'%Y-%m-%d') = '$DateTime_1'";
}
$result = $conn->query($strSql);
} else {
$strSql = "INSERT INTO manufacturejobschedulingpersonal (string_20_1,string_20_2,YM,DateTime_1,String_10_1,String_Assist01,String_Assist02)".
"VALUES ( '$UserId', '$UserName', '$YM', '$DateTime_1', '$String_10_1','$assist_1','$assist_2')";
$result = $conn->query($strSql);
}
.
.//A lot of sql CRUD
.
}
}
$conn->close();
$last_line = exec('java -jar C:/CCERP/ChainCodeERP/ExtraModule/HRMultiOTCheck/HRMultiOTCheck.jar -ssa '.$javaDate.' ' .$javaDepId, $return_var);
echo 'Updated';
?>

Select last registred user from database

I have a problem trying to select the last registered user. I'm trying to print newly registered users to the screen - can anyone help?
<?php
if (isset($_POST['registrovat']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$passwordre = $_POST['passwordrepeat'];
$email = $_POST['email'];
if ($password == $passwordre)
{
if ($username && $email)
{
$password = md5(sha1(md5($password)));
$db_servername = "localhost";
$db_username = "kubaaivcaweb";
$db_name = "insanity";
$db_password = "XXXXX";
$username = $_POST['username'];
$ip = $_SERVER['REMOTE_ADDR'];
$db_conn = mysqli_connect($db_servername, $db_username, $db_password, $db_name);
$query = mysqli_query($db_conn, "INSERT INTO `8` SET username='$username', password='$password', ip='$ip', email='$email'");
echo "Registrace proběhla úspěšně";
}
}
else {
echo "Hesla se neshodují!";
}
}
while ($row = mysqli_fetch_assoc($new))
{
$new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC");
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
You have put your query inside instead of outside your loop. Your code looks like this:
while ($row = mysqli_fetch_assoc($new)) {
$new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC");
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
Instead it should look like this:
echo "DEBUG before query<br />"
if (! $new = mysqli_query($db_conn, "SELECT * FROM `8` ORDER BY `id` DESC")) {
echo "DB error: ". mysqli_error($db_conn). "<br />" ;
exit 1;
}
echo "DEBUG after query<br />"
while ($row = mysqli_fetch_assoc($new)) {
echo "<p>Nejnovější uživatel:" . $row['username'] . "</p>";
}
echo "DEBUG after fetch<br />"

Categories