Hello i am seen lot of question like Session doesn't working first time. But couldn't see any good explanation on this question and why doesn't working first time also what is happening during sessioning. Mine is also like others first time doesn't working after that works fine.
this is php which is sessioning.
session_start();
$PersonName=$_GET['PersonName'];
$SurName=$_GET['SurName'];
$TestXML=$_GET['TestXML'];
$TestDate=$_GET['TestDate'];
$TestPkID='0000000000000000000000000000';
include('DBConnect.php');
$proc = "{call p_set_Test(?,?,?,?,?,?,?,?,?)}";
$params = array(array($TestDate,SQLSRV_PARAM_IN),
array(0,SQLSRV_PARAM_IN),
array($PersonName,SQLSRV_PARAM_IN),
array($SurName,SQLSRV_PARAM_IN),
array($TestXML,SQLSRV_PARAM_IN),
array('',SQLSRV_PARAM_IN),
array(101,SQLSRV_PARAM_IN),
array(10,SQLSRV_PARAM_IN),
array($TestPkID, SQLSRV_PARAM_OUT)
);
$result = sqlsrv_query( $conn, $proc, $params);
if( $result === false )
{
echo "Error in executing statement 3.\n";
die( print_r( sqlsrv_errors(), true));
$message2 = "aldaatai";
echo "<script type='text/javascript'>alert('$message2 ' + $TestPkID);</script>";
}
$_SESSION['idpktestsession'] = $_POST["idpktest"] = $TestPkID;
$_SESSION['persontestname'] =$_POST['persontrollname'] = $PersonName;
$_SESSION['persontestlastname'] =$_POST['persontrolllastname'] = $SurName;
this is getting value from sessioned values
<?php include('DBConnect.php');
session_start();
$diskuserid = $_SESSION['idpktestsession'];
$diskusername = $_SESSION['persontestname'];
$diskuserlastname = $_SESSION['persontestlastname'];
$diskuserlastname = mb_substr($diskuserlastname, 0, 1);
?>
<?php
$proc = "{call p_rpt_Pattern(?,?)}";
$params = array($diskuserid,'M');
$procarr = array();
$result = sqlsrv_query( $conn, $proc, $params);
while ($row = sqlsrv_fetch_array($result))
{?>
<tr>
<td><?php echo $row['PatternCode']?></td>
<td><i class="fa fa-chevron-right rightarrow" > </i></td>
<td><?php echo $row['PatternDesc']?></td>
</tr>
<?php
}
?>
This statement was written incorrect:
$_SESSION['idpktestsession'] = $_POST['idpktest'] = $TestPkID;
If you want to assign the value you can rewrite above statement like this
$_SESSION['idpktestsession'] = $_POST['idpktest'];
and if you want to concatenate two values you can rewrite like this
$_SESSION['idpktestsession'] = $_POST['idpktest'] . ','. $TestPkID;
As long this is question wasn't answered i found why it don't work first time.
Everytime it sending session to another php with value ,its sending with value after page load so if you some how face this error just assign value before page load or put middle loading php insteand of showing direct.
Related
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 pass a variable from one page to another using $_GET, and I can't seem to get it to work. I would appreciate any help.
First I create a link based on the results from the database here.
clients.php
require_once("../auth/config.class.php");
require_once("../auth/auth.class.php");
$config = new Config;
$dbh = new PDO("mysql:host={$config->dbhost};dbname={$config->dbname}", $config->dbuser, $config->dbpass);
$auth = new Auth($dbh, $config);
$uid = $auth->SessionUID($_COOKIE['authID']);
$query = $dbh->prepare("SELECT fname, lname, id FROM client WHERE uid=? ORDER by id");
$query->execute(array($uid));
$rslt = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($rslt as $row ){
echo "<a href=../pages/status.php?id=$row[id]>$row[fname]<br></a>";
}
The result from the link are listed on this page
status.php
$cid = $_GET['id'];
$query = $dbh->prepare("SELECT function FROM funcbathing WHERE cid=?");
$query->execute(array($cid));
$rslt = $query->fetch(PDO::FETCH_ASSOC);
if (empty($rslt)){
header('Location: ../views/careplan.php');
echo $cid
}
else{
header('Location: ../views/home.php');
}
I would like to pass the $cid to this page in a text box, but I can't seem to get it work. Here's the page that the id should get passed to.
careplan.php this is a bigger form but I removed the irrelevant information for simplicity.
<input type="text" name="clientid" value="<?php if(isset($_GET['cid'])) { echo $_GET['cid']; } ?>" />
header('Location: ../views/careplan.php?cid='.$cid);
EDIT:
You should learn to print the strings in a valid manor, check error_reporting(E_ALL); and display_errors=on with your string.
then try this:
echo ''.$row["fname"].'<br>';
or:
echo sprintf('%s<br>', $row['id'], $row['fname']);
or even:
echo "{$row["fname"]}<br>";
or any of the other hundreds way to write a valid string
I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);
This question already has answers here:
Get number of rows in SQL-Server with PHP
(2 answers)
Closed 9 years ago.
I know there have been lots of questions about this but I need some specific help, I'm new to sql and php, so sorry for bad coding and poor indenting. What I am trying to do is count the number of rows to a specific column then when I find out how many have this id from this column then I would like it to send this number back to the php page. ATM I am using a like query I don't want this effected.
My layout is 3 pages the index the part choices and the part location, the user inputs a part number into the index page which is then searched against the database which then displays the parts that match or are like the users input on the part choices page. then you click on the part you want and then it takes you to the locations page and showing the closest locations for this part.
What I am trying to do is when the user puts in the part number a query runs and searches the database counting the number of rows that have or are like the input, then outputs the parts like it usually does, but what i want to happen is if there is only one row with that part number i want it to say row = 1 so i can then run an if statement using this value. i have looked into different code and cant quiet find what I'm looking for these are the examples I have found and have tryied to modify for what I need. but i have had no luck.
$query = "SELECT (column) FROM table WHERE column = value";
2.$results = mysql_query($query);
3.$rows = mysql_num_rows($results);
4.echo $rows ;
seperate code below
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
i would like the code or query to be within the php that i have, any ideas would be great or examples sorry about poor english many thanks
my code for my page is below:
<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=false;">
<script type="text/javascript">
function submit()
{
document.getElementById("start").click(); // Simulates button click
document.submitForm.submit(); // Submits the form without the button
}
</script>
</head>
<body>
<?php
try {
$serverName = "188.64.188.89";
$connectionInfo = array( "Database"=>"tdStoreLocator", "UID"=>"odbcAdmin", "PWD"=>"Midnight1Midnight1");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false )
{
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT TOP 10 [company]
,[partnum]
,[description]
FROM [tdStoreLocator].[odbcadmin].[Part]
WHERE Part.partnum LIKE ? or Part.description LIKE ?";
/* Set parameter values. */
$params = array( "%" . str_replace(" ","%",$_POST["part"] ). "%", "%" . str_replace(" ","%",$_POST["part"] ) . "%");
$i = 0;
$x = true;
/*echo print_r($params, true);*/
$stmt = sqlsrv_query( $conn, $sql, $params );
if( $stmt === false)
{
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
if($x == true)
{
echo"<form id=\"submitForm\" action=\"locations.php\" method=\"post\">";
echo"<input type=\"hidden\" name=\"part\" id=\"3\" value=\"".$row['partnum']."\">";
echo"<input type=\"hidden\" name=\"lon1\" id=\"1\" value=\"".$_POST["lon1"]."\">";
echo"<input type=\"hidden\" name=\"lat1\" id=\"2\" value=\"".$_POST["lat1"]."\">";
echo"<button id=\"start\" type=\"submit\">";
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['partnum']."<br/>";
echo "</div>";
echo"<img style=\"width:50%;\"; src=\"productimages/".$row['partnum'].".jpg\" alt=\"Save icon\" onError=\"this.src='productimages/noimage.jpg'\"/>";
echo "<div style=\"font-family:verdana;color:#3083FF;font-size:20px;width:100%;text-align:center;margin:0; padding:0;\">";
echo $row['description'];
echo "</div>";
echo"</button>";
echo"</form>";
}
$i++;
}
sqlsrv_free_stmt( $stmt);
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
if($i < 1)
{
echo "<div style=\"font-family:verdana;font-weight:bold;color:#3083FF;font-size:20px;width:100%;text-align:center;\">";
echo "No results found, Please check your spelling of the part number or description.";
echo "</div>";
}
if($i == 1 ) {
echo"<img onload=\"setTimeout(submit(),00001);\" src=\"index.jpg\" onError=\"this.src='productimages/noimage.jpg'\"/>";
}
?>
</body>
</html>
Instead you can use count in query.
$query = "SELECT count(column) FROM table WHERE column = value";
following step count search value in mysql table.
$query = "SELECT * FROM table WHERE fieldName = fieldvalue";
$results = mysql_query($query);
$rows = mysql_num_rows($results);
echo $rows ;
Why is this not working?
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
$result = mysqli_fetch_assoc($query);
$title = mysqli_real_escape_string($connect,trim($result['title']));
$message = mysqli_real_escape_string($connect,trim($result['message']));
while(($result = mysqli_fetch_assoc($query))){
echo $title;
echo '<br/>';
echo '<br/>';
echo $message;
}
?>
where as this works -
<?php
echo $title;
?>
SORRY TO SAY, BUT NONE OF THE ANSWERS WORK. ANY OTHER IDEAS?
If your mysqli query is returning zero rows then you will never see anything printed in your while loop. If $title and $message are not set (because you would want reference them by $result['title'] & $result['message'] if that are the field names in the database) then you will only see two <br /> tags in your pages source code.
If the while loop conditional is not true then the contents of the while loop will never execute.
So if there is nothing to fetch from the query, then you won't see any output.
Does you code display anything, or skip the output entirely?
If it skips entirely, then your query has returned 0 rows.
If it outputs the <br /> s, then you need to check your variables. I could be wrong, not knowing te entire code, but generally in this case you would have something like
echo $result['title'] instead of echo $title
If $title and $message come from your mysql query then you have to access them through the $result array returned by mysqli_fetch_assoc.
echo $result['title'];
echo $result['message'];
Also if your using mysqli you'd be doing something like this:
$mysqli = new mysqli("localhost", "user", "password", "db");
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_assoc()) {
print $row['title'];
}
$result->close();
}
Try this:
<?php
$result = mysql_query($query);
while($row = mysqli_fetch_assoc($result)){
echo $title.'<br/><br/>'.$message;
}
?>
Does this work;
<?php
$select = "select * from messages where user='$u'";
$query = mysqli_query($connect,$select) or die(mysqli_error($connect));
$row = mysqli_num_rows($query);
while(($result = mysqli_fetch_assoc($query))){
echo $result['title'];
echo '<br/>';
echo '<br/>';
echo $result['message'];
}
?>
Basically I've made sure that it's not picking the first result from the query & then relying on there being more results to loop through in order to print the same message repeatedly.