Here I've written my code in the search.php file
if(isset($_POST['searchField'])){
$searchName = UserManager::searchName();
if(empty($_POST['searchField'])){
$error = 'Typ a name';
}else{
if(!isset($_POST['searchName'])){
$error = 'No result';
} else{
foreach($searchName as $name){
$succes = $name['firstName'] . " ". $name['lastName'];
}
}
}
}
Here is a part of the HTML where it prints the full names.
<div class="form-group">
<?php if(isset($error)): ?>
<p>
<?php echo $error; ?>
</p>
<?php endif; ?>
<?php if(isset($succes)): ?>
<p>
<?php echo $succes; ?>
</p>
<?php endif; ?>
</div>
Here is my function:
public static function searchName()
{
$conn = Db::getConnection();
$searchField = $_POST['searchField'];
$statement = ("SELECT * from tl_user WHERE firstname = :name OR lastname = :name");
$query = $conn->prepare($statement);
$query->bindValue(':name', $searchField);
//var_dump($searchField);
$query->execute();
//"SELECT * from tl_user WHERE firstName LIKE '%$searchName% OR lastName LIKE '%$searchName%"
$count = $query->fetchAll(PDO::FETCH_ASSOC);
var_dump($count);
return $count;
}
My question exactly is: if there are more people with the same lastName, it prints only 1 full name instead of several names.
In my function I've put 'var_dump($count);' to see if there is more than 1 array and there is, but it doesn't print
I'm a beginner, so I'm still learning :)
concatenate values into $succes using .= rather than overwriting it each time round the loop
$succes = '';
foreach($searchName as $name){
$succes .= $name['firstName'] . " ". $name['lastName'];
}
I'm having a problem getting a result from my mysql database and getting it to popular a form. Basically, i'm making an item database where players can submit item details from a game and view the database to get information for each item. I have everything working as far as adding the items to the database and viewing the database. Now i'm trying to code an edit item page. I've basically reused my form from the additem page so it is showing the same form. At the top of my edititem page, I have the php code to pull the item number from the url as the item numbers are unique. So i'm using a prepared statement to pull the item number, then trying to retrieve the rest of the information from the database, then setting each information to a variable. Something is going on with my code but I can't find any errors. I entered a few header calls to debug by putting information in the url bar...But the headers aren't even being called in certain spots and im not getting any errors.
In the form, I used things like
<input name="itemname" type="text" value="<?php $edit_itemname?>">
and nothing is showing in the textbox. I'm fairly new to php and it seems much more difficult to debug than the other languages i've worked with..Any help or suggestions as far as debugging would be greatly appreciated. I posted my php code below as well if you guys see anything wrong...I shouldn't be having issues this simple! I'm pulling my hair out lol.
Thanks guys!
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
}else{
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
}else{
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
}else{
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
header("Location: edititem.php?testing");
}
}
}
}
?>
To get the value of $edit_itemname into the output you should be using <?= not <?php. Saying <?php will run the code, so basically that is just a line with the variable in it. You are not telling it to print the value in the variable.
If your whole line looks like:
<input name="itemname" type="text" value="<?= $edit_itemname?>">
That should give you what you are looking for. The <?= is the equivalent of saying echo $edit_itemname;
If you don't like using <?= you could alternatively say
<input name="itemname" type="text" value="<?php echo $edit_itemname; ?>">
Your code should be change to a more readable form and you should add an output - I wouldn't recomment to use <?= - and you need to choose what you're going to do with your rows - maybe <input>, <table> - or something else?
<?php
require 'dbh.php';
if (!isset($_GET['itemnumber'])) {
header("Location: itemdb.php");
exit();
} // no else needed -> exit()
$sql = "SELECT * FROM itemdb WHERE id = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: edititem.php?error=sqlerror");
exit();
} // no else needed -> exit()
$getid = $_GET['itemnumber'];
mysqli_stmt_bind_param($stmt, "i", $getid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
//Make sure an item is selected
if ($result == 0) {
$message = "You must select an item to edit!";
header("Location: edititem.php?Noresults");
exit();
} // no else needed -> exit()
while ($row = mysqli_fetch_assoc($stmt)) {
$edit_itemname = $row['name'];
$edit_itemkeywords = $row['type'];
$edit_itemego = $row['ego'];
$edit_itemweight = $row['weight'];
$edit_itemacordmg = $row['acordmg'];
$edit_itemtags = $row['tags'];
$edit_itemworn = $row['worn'];
$edit_itemaffects = $row['affects'];
$edit_itemloads = $row['loads'];
$edit_itemarea = $row['area'];
$edit_itemcomments = $row['comments'];
// does not make sense here: header("Location: edititem.php?testing");
// show your data (need to edited):
echo "Name: " + $edit_itemname + "<br/>";
echo "Area: " + $edit_itemarea + "<br/>";
echo "Comment: " + $edit_itemcomments + "<br/>";
// end of current row
echo "<hr><br/>"
}
?>
I am trying to display results of a mysql query and some html if the first mysql queries coulmn returns false or is set to false. I've tried a few things but I can't seem to get it to work properly, I will show code below. Any help is much appreciated. In the code I want to only display site message if the user's acknowledgement is false otherwise don't display anything.
function siteWideMessage()
{
global $dbh;
$siteMessage = "";
$sUserInfo = $dbh->prepare("
SELECT acknowledgement
FROM user
WHERE uid = :uid
");
$sUserInfo->bindValue(":uid", $_SESSION["uid"]);
if ($sUserInfo->execute()) {
$res = $sUserInfo->fetch();
if ($res["acknowledgement"] = false) {
$stmt = $dbh->query("
SELECT message
FROM SiteWideMessages
ORDER BY idSiteWideMessages DESC
LIMIT 1
");
while ($row = $stmt->fetch()) {
$siteMessage .= "
<div class='siteMessage'>
<span>" . $row["message"] . "</span>
<br><br>
<span style='font-weight:normal;'>I acknowledge that I have read this important site message</span>
<br>
<input type='submit' name='submit' value='I Agree'></input>
</div>";
}
}
$sUserInfo->closeCursor();
}
if (isset($_POST["submit"])) {
$stmt = $dbh->prepare("
UPDATE user
SET `acknowledgement` = 'true'
WHERE uid = :uid
");
$stmt->bindValue(":uid", $_SESSION["uid"]);
if($stmt->execute()) {
$stmt->closeCursor();
}
}
return $siteMessage; }
UPDATE:
I managed to get it working the way I want it to I just had to do as the following.
if ($res["acknowledgement"] == 'false')
Thanks for everyone's help!
You are missing an = in your if statement. It should be:
...
if ($res["acknowledgement"] === false) {
...
i am making a profile.php page and i would like it to show the user all his projects, this is my first time doing something like this, and i cant find a solution for it
code to show the projects :
$username = $_SESSION['username'];
if ($_SESSION['type'] = "developer"){
$q = "SELECT * FROM `projects` WHERE `developer` = '$username'";
$result = mysqli_query($con,$q);
$row = mysqli_fetch_array($result);
$numrows = mysqli_num_rows($result);
if(empty($numrows)){
echo'
<div class="row">
<div class="col-lg-12 newp">
<p><span class="glyphicon glyphicon-plus plus"></span>Add a new project</p>
</div>
</div>';
}else{
$p_id = $row['project_id'];
$p_name = $row['project_name'];
$p_owner = $row['owner'];
$p_developer = $row['developer'];
$p_price = $row['price'];
$p_date_started = $row['date_started'];
$p_date_end = $row['date_end'];
$p_paid = $row['paid'];
//foreach project the user has do this :
echo"
<div class=\"row\">
<div class=\"col-lg-12\">
<p>$p_name </br>owner : $p_owner, developer : $p_developer, price : $p_price$</br>started : $p_date_started, ends :$p_date_end, paid :$p_paid</p>
</div>
</div>";
}
}
} else {
while($row = mysqli_fetch_array($result)) {
$p_id = $row['project_id'];
...
Besides the other answer given:
You're presently assigning instead of comparing with
if ($_SESSION['type'] = "developer"){...}
^
which the above will fail and everything inside that conditional statement and should read as
if ($_SESSION['type'] == "developer"){...}
^^
with 2 equal signs.
Make sure the session has also been started, it's required when using sessions.
session_start();
You're also open to an SQL injection. Use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
UPDATE: NOW RESOLVED - Thanks everyone!
Fix: I had a column named "referred_by" and in my code it's called "referred_by_id" - so it was trying to INSERT to a column that didn't exist -- once I fixed this, it decided to work!
I have limited time left to work on this project. The clock is ticking.
I'm trying to INSERT $php_variables into a TABLE called "clients".
I've been trying for hours to get this script to work, and I got it to work once, but then I realized I forgot a field, so I had to add another column to the TABLE and when I updated the script it stopped working. I reverted by but now it's still not working and I'm just frustrating myself too much.
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
if (!isset($_COOKIE["user"]))
{
header ("Location: ./login.php");
}
else
{
include ("./source.php");
echo $doctype;
}
$birthday = $birth_year . "-" . $birth_month . "-" . $birth_day;
$join_date = date("Y-m-d");
$error_type = 0;
$link = mysql_connect("SERVER", "USERNAME", "PASSWORD");
if (!$link)
{
$error = "Cannot connect to MySQL.";
$error_type = 1;
}
$select_db = mysql_select_db("DATABASE", $link);
if (!$select_db)
{
$error = "Cannot connect to Database.";
$error_type = 2;
}
if ($referred_by != "")
{
$result = mysql_query("
SELECT id FROM clients WHERE referral_code = $referred_by
");
if (!$result)
{
$error = "Cannot find referral.";
$error_type = 3;
}
while ($row = mysql_fetch_array($result))
{
$referred_by_id = $row['id'];
}
}
else
{
$referred_by_id = 0;
}
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$birth_month = mysql_real_escape_string($_POST['birth_month']);
$birth_day = mysql_real_escape_string($_POST['birth_day']);
$birth_year = mysql_real_escape_string($_POST['birth_year']);
$email = mysql_real_escape_string($_POST['email']);
$address = mysql_real_escape_string($_POST['address']);
$city = mysql_real_escape_string($_POST['city']);
$state = mysql_real_escape_string($_POST['state']);
$zip_code = mysql_real_escape_string($_POST['zip_code']);
$phone_home = mysql_real_escape_string($_POST['phone_home']);
$phone_cell = mysql_real_escape_string($_POST['phone_cell']);
$referral_code = mysql_real_escape_string($_POST['referral_code']);
$referred_by = mysql_real_escape_string($_POST['referred_by']);
$organization = mysql_real_escape_string($_POST['organization']);
$gov_type = mysql_real_escape_string($_POST['gov_type']);
$gov_code = mysql_real_escape_string($_POST['gov_code']);
$test_query = mysql_query
("
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."')
");
if (!$test_query)
{
die(mysql_error($link));
}
if ($error_type > 0)
{
$title_name = "Error";
}
if ($error_type == 0)
{
$title_name = "Success";
}
?>
<html>
<head>
<title><?php echo $title . " - " . $title_name; ?></title>
<?php echo $meta; ?>
<?php echo $style; ?>
</head>
<body>
<?php echo $logo; ?>
<?php echo $sublogo; ?>
<?php echo $nav; ?>
<div id="content">
<div id="main">
<span class="event_title"><?php echo $title_name; ?></span><br><br>
<?php
if ($error_type == 0)
{
echo "Client was added to the database successfully.";
}
else
{
echo $error;
}
?>
</div>
<?php echo $copyright ?>
</div>
</body>
</html>
Definitely not working as is. Looks you have a 500 error, since you have an else with a missing if:
else
{
$referred_by_id = 0;
}
Otherwise, you'll need to post your DB schema.
Also, note that you're really taking the long way around with this code, which makes it difficult to read & maintain. You're also missing any sort of checks for SQL injection... you really need to pass things through mysql_real_escape_string (and really, you should use mysqli, since the mysql interface was basically deprecated years ago).
$keys = array('first_name',
'last_name',
'birthday',
'join_date',
'email',
'address',
'city',
'state',
'zip_code',
'phone_home',
'phone_cell',
'referral_code',
'referred_by_id',
'organization',
'gov_type',
'gov_code');
$_REQUEST['birthdate'] = $_REQUEST['birth_year'].'-'.$_REQUEST['birth_month'].'-'.$_REQUEST['birth_day'];
$_REQUEST['join_date'] = date('Y-m-d',time());
$params = array();
foreach ($keys as $key)
{
$params[] = mysql_real_escape_string($request[$key]);
}
$sql = 'INSERT INTO clients ('.implode(',', $keys).') ';
$sql .= ' VALUES (\''.implode('\',\'', $params).'\') ';
You've an error on line 81:
else
{
$referred_by_id = 0;
}
I don't see an IF construct before that, make the appropriate correction and run the script again.
Without looking at the table structure to make sure all the fields are there, I'm going to assume it's something with the data.
Any quotes in the data will lead to problems (including SQL injection security holes). You should wrap each $_POST[] with mysql_real_escape_string(), such as:
$first_name = mysql_real_escape_string($_POST['first_name']);
EDIT: Further debugging...
As someone suggested (sorry, can't find the comment), try:
$sql = "
INSERT INTO clients (first_name, last_name, birthday, join_date, email, address, city, state, zip_code,
phone_home, phone_cell, referral_code, referred_by_id, organization, gov_type, gov_code)
VALUES ('".$first_name."', '".$last_name."', '".$birthday."', '".$join_date."', '".$email."', '".$address."', '".$city."', '".$state."', '".$zip_code."',
'".$phone_home."', '".$phone_cell."', '".$referral_code."', '".$referred_by_id."', '".$organization."', '".$gov_type."', '".$gov_code."'
)";
// Debug:
print "<pre>". $sql ."</pre>";
mysql_query($sql);
The SQL statement should be printed out when submitting the form. Take that SQL statement and try to execute it directly in MySQL to see if it works, or if it generates an error.