Select last registred user from database - php

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 />"

Related

trying to check if user exists with php

hi i am trying to make a php script that checks if a user is in the database only it gives me the error
mysqli_num_rows() expects parameter 1 to be mysqli_result, bool given in C:\xampp\htdocs\stage\userExist.php on line 22
below is the code
<?php
$link = mysqli_connect('localhost', 'root', '', 'k3462_top-tree');
$query = "SELECT * FROM users";
$userName = $_GET['userName'];
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['userName'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
$query1 = "SELECT * FROM users WHERE userName = $userName";
$result1 = mysqli_query($link, $query1);
if(mysqli_num_rows($result1)>=1){
echo "user exists";
}
else {
echo "user doesnt exist";
}
mysqli_close($link);
?>
You have a syntax error in your query that fill the variable $result1 with false. That occurs your error. Try my example below. I just added ' around $userName in your query and an if statement around your mysqli_num_rows function.
$link = mysqli_connect('localhost', 'root', '', 'k3462_top-tree');
$query = "SELECT * FROM users";
$userName = $_GET['userName'];
$result = mysqli_query($link, $query);
echo "<table>";
while($row = mysqli_fetch_array($result)){
echo "<tr><td>" . $row['userName'] . "</td><td>" . $row['email'] . "</td></tr>";
}
echo "</table>";
$query1 = "SELECT * FROM users WHERE userName = '$userName'";
$result1 = mysqli_query($link, $query1);
if( $result1 ) {
if(mysqli_num_rows($result1)>=1){
echo "user exists";
}
else {
echo "user doesnt exist";
}
} else {
echo "query or db error";
}
mysqli_close($link);
$query1 = "SELECT * FROM users WHERE userName = '$userName'";

assigned $output from search form not printing

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);
?>

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';
?>

If 0 items in DB table, return error

I am looking for a way to display an error message if there is nothing listed in the table.
I have a photos table.
If this tables is empty, id like to echo something.
else, show the pictures.
inside of that table I have
id, name, url
id = id
name = name of image
url = url of image.
If there are no rows, we have an error.
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
mysql_fetch_array($query1);
if(empty($query1)) {
echo "nothing";
} else {
echo "good";
}
Try this,
$query = "SELECT * FROM photos";
$result= mysql_query($query);
$length= mysql_num_rows($result);
if($length>0)
{
while($rows = mysql_fetch_array($result))
{
echo $rows['name'];
echo "<img src='$rows[url]' />";
}
}
else
{
echo "Nothing to display";
}
Hope this will work
What about something like...
$sql = "SELECT COUNT(*) AS amountPhotos FROM photos";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row["amountPhotos"] == 0) {
echo "There are no photos in the photo table.";
}
or
$sql = "SELECT * FROM photos LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0) {
echo "There are no photos in the photo table.";
}
Try this
$query1 = mysql_query("SELECT COUNT(*) FROM photos;");
$result = mysql_fetch_array($query1);
if(empty($result)) {
echo "nothing";
} else {
echo "good";
}
This pretty much sums up the answer for this question: http://www.w3schools.com/php/php_mysql_select.asp
They even provided a sample code:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = $conn->query($sql);
if ($result->num_rows > 0) { //<--- here they check if number of rows returned is greater than 0 (so there is data to display)
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results"; //<----- nothing found
}
$conn->close();
?>
Just modify this and you'll be good to go.

SQL query not functioning correctly, getting no output with a perfectly fine query

code:
<?php
session_start();
if ( isset($_GET['user']) && isset($_GET['pass']) )
{
$sql = "SELECT * FROM `users` WHERE `name` = '" . $_GET['user'] . "' AND `password` = '" . $_GET['pass'] . "';";
echo("query: $sql <br />");
$db = mysqli_connect("localhost", "root", "<password here>", "1596");
if (mysqli_connect_errno($db)) { die("err"); }
$result = mysqli_query($db, $sql);
echo($query);
$row = mysqli_fetch_aray($result);
echo($row);
if ($row['name'] == $_GET['user'])
{
$_SESSION['uid'] = $row['name'];
$_SESSION['level'] = $row['level'];
echo("logged in as " . $_SESSION['uid']);
}
}
else
{
die("Error, not enough parameters");
}
?>
If I run that query on server, it is fine.. there is no connect error, so wondering where I went wrong
$db = mysqli_connect("localhost", "root", "<password here>", "1596");
if (mysqli_connect_errno($db)) { die("err"); }
$result = mysqli_query($db, $sql); // line corrected
$row = mysqli_fetch_array($result); // line corrected

Categories