PHP-Linking forms Using ID - php

I have a database in which I have a main form that list all personnel using this code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("datatest", $con);
$result = mysql_query("SELECT * FROM Personnel");
echo "<TABLE BORDER=2>";
echo"<TR><TD><B>Name</B><TD><B>Number</B><TD><B>View</B><TD></TR>";
while ($myrow = mysql_fetch_array($result))
{
echo "<TR><TD>".$myrow["Surname"]." ".$myrow["First Names"]."<TD>".$myrow["Number"];
echo "<TD>View";
}
echo "</TABLE>";
?>
</HTML>
As you can note I have a link to view details of the person but when I click on the VIEW link I get the following error
Parse error: syntax error, unexpected 'EmployeeID' (T_STRING) in C:\Program Files\EasyPHP-12.1\www\my portable files\dss4\childdetails.php on line 6
The childdetails.php has the following code
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children;
WHERE "EmployeeID="["$EmployeeID"],$db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>
Since the first form to list the personnel works I believe the problem is in childdetails.php on line 6 as returned by the server but I simply don’t know how to fix it.
Note: a person can have more than one child as well as having more than one wife
Help please

I would say more like.
$result = mysql_query("SELECT * FROM children WHERE EmployeeID='$EmployeeID'");
// as far $EmployeeID is actualy set before running a query
//but as comment says don't use mysql better something like this
<?php
$mysqli = new mysqli('localhost', 'root', 'my_password', 'my_db');
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
/* create a prepared statement */
if ($stmt = $mysqli->prepare("SELECT * FROM children WHERE EmployeeID=?")) {
/* bind parameters for markers */
$stmt->bind_param("s", $EmployeeID);
/* execute query */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($Employee);
/* fetch value */
$stmt->fetch();
printf($Employee);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();

To begin with, your query is wrong, you're telling the sql that your script is over and that it should start executing something new. I'll show you how to do it properly here below.
Also, don't use mysql specific syntax, It's outdated and can get you into real trouble later on, especially if you decide to use sqlite or postgresql.
Also, learn to use prepared statements to avoid sql injection, you want the variables to be used as strings into a prepared query, not as a possible executing script for your sql.
Use a PDO connection, you can init one like this:
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
And then init the variables:
$host = 'localhost';
$user = 'root';
$dataBaseName = 'databaseName';
$pass = '';
Now you can access your database via
$db = connectToDatabase($host , $databaseName, $user, $pass); // You can make it be a global variable if you want to access it from somewhere else.
Now you should construct a query that can be used as a prepared query, that is, it accepts prepared statements so that you prepare the query and then you execute an array of variables that are to be put executed into the query, and will avoid sql injection in the meantime:
$query = "SELECT * FROM children WHERE EmployeeID = :employeeID;"; // Construct the query, making it accept a prepared variable.
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(':employeeID' => $EmployeeID)); // Here you insert the variable, by executing it 'into' the prepared query.
$statement->setFetchMode(PDO::FETCH_ASSOC); // Set the fetch mode.
while ($row = $statement->fetch())
{
$ChildName = $row['ChildName'];
$Mother = $row['Mother'];
$DateOfBirth = $row['DateOfBirth'];
echo "Child Name: $ChildName";
echo "<br />Mother: $Mother";
echo "<br />Date of Birth: $DateOfBirth";
}
You should use a similar approach to receive $EmployeeID but this should help you a lot.
By the way: remember to close your break tags with a whitespace ' ' and a forwardslash like I showed you.

You
Need
change your query something like this
<HTML>
<?php
$db = mysql_connect("localhost", "root", "");
mysql_select_db("datatest",$db);
$result = mysql_query("SELECT * FROM children WHERE EmployeeID=" . $EmployeeID, $db);
$myrow = mysql_fetch_array($result);
echo "Child Name: ".$myrow["ChildName"];
echo "<br>Mother: ".$myrow["Mother"];
echo "<br>Date of Birth: ".$myrow["DateOfBirth"];
?>
</HTML>

Related

What is the correct MySQL database statement where the variable defined as all the rows

I try to explain this well folks,
I have a database with 20 questions with two principles : 1) Cardiology and 2) Endocrine. And you can select using HTML selection menu either of the concepts or you can select 3) All.
And on my html page I have a selection menu with 3 options and they each have a value:
<div id="selectContainer1">
<select id="selectedPrinciple" name="selectedPrinciple">
<option value="" disabled="disabled" selected="selected">Select a System</option>
<option value="">All</option>
<option value="VASCULAR">Cardiology, Vascular System</option>
<option value="ENDOCRINE">Endocrine</option>
</select>
</div>
<input type="submit" value="Start">
I have this code on php:
$selectedPrinciple = $_POST['selectedPrinciple'];
$sql = ("SELECT * FROM qbanktable WHERE Principle = '$selectedPrinciple'"
Now when I select option "Cardiology" or "Endocrine", all the rows that are related to those are picked from my database and showed on the next page. But when I select "All" I get a syntax error because of course as it does have no value the row cannot be found on my database. Is there anything I can put for the option value for "All" that the mysql returns all the rows?
You could check if $selectedPrinciple is empty() and modify the query accordingly.
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// this line indicates that you don't use prepared statements
$sql = "SELECT * FROM `qbanktable` WHERE `Principle` = '$selectedPrinciple'";
} else {
$sql = "SELECT * FROM `qbanktable`";
}
full example using mysqli prepared statement
$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);
}
$selectedPrinciple = $_POST['selectedPrinciple'];
if(!empty($selectedPrinciple)) {
// prepare and bind
$stmt = $conn->prepare("SELECT * FROM `qbanktable` WHERE `Principle` = ?");
$stmt->bind_param("s", $selectedPrinciple);
} else {
// prepare
$stmt = $conn->prepare("SELECT * FROM `qbanktable`");
}
// execute
$stmt->execute();
// fetch data
if (!($res = $stmt->get_result())) {
echo "Failed to fetch the result set: (" . $stmt->errno . ") " . $stmt->error;
}
// print data
print_r($res->fetch_all());
// close prepared statement
$stmt->close();
// close connection
$conn->close();
Personally, I like to use a few techniques to "build" my query, like so:
NOTE:
I'm demonstrating how to do this with PDO and parameter binding, because your query is open to SQL injection attacks.
$sql = "SELECT * FROM `qbanktable`";
$where = [];
$params = [];
if ( ! empty( $_POST['selectedPrinciple'] ) ) {
$where[] = '`Principle` = ?';
$params[] = $_POST['selectedPrinciple'];
}
if ( /* some other condition */ ) {
// add to the $where / $params as appropriate
}
// Glue the $where into a string
$where = implode( ' AND ', $where );
// Append where to the $sql statement
$sql .= ( $where ) ? ' WHERE ' . $where : '';
// assumes $conn is already a set-up PDO connection
$stmt = $conn->prepare( $sql );
$stmt->execute( $params );
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
I think the best way is to check in PHP if the value of selectedPrinciple is something like ALL or is empty, and then don´t add the WHERE part of the query.
If really want to use some value for All option, you can try to use one or two percents signs '%' or '%%', but I don´t remember if it works. However, I don´t recommend this approach. Take care also about SQL Injection.

I can't connect to db or pull data

I am using this same code `
php $postId = 41;
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname="my_db";
$host="localhost";
$user="guessthe";
$dbh=mysql_connect ($host,$user,"correctPassword?") or die ('I cannot connect to the database because: ' . mysql_error(). '');
mysql_select_db ("$dbname") or die('I cannot select the database because: ' . mysql_error());
$sql="SELECT * FROM games WHERE postId = $postId";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
There is a value in the gameLength row! I can't get this code to pull any of the rows! Any idea what i'm doing wrong?
You're using MySQL, which is depcirated - and will be phased out. You should use MySQLi or PDO instead. Also, your $postId is defined outside a PHP-tag? Might just be a copy/paste mistake? Anyway, you can try the code below, which is in MySQLi:
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength"><?php
// MySQL connect configuration
$dbname = "my_db";
$host = "localhost";
$user = "guessthe";
// Connecting to the database
$mysqli = new mysqli($host, $user, "correctPassword?", $dbname);
if ($mysqli->connect_errno) {
// If we are here, the connection failed
echo "Failed to connect to MySQL: (".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql ="SELECT * FROM games WHERE postId = $postId";
if ($result = $mysqli->query($sql)) {
// If the query was sucsessfull, we can get the rows
while ($row = $result->fetch_assoc()) {
$gameId = $row['id'];
$game100s = $row['game100s'];
$gamesPlayedAllTime = $row['gamesPlayed'];
$gamesPointsAllTime = $row['gameScore'];
$gameLength = $row['gameLength']; // get number of questions
$gameScore = $row['gameScore'];
$gameType = $row['gameType'];
$gametitle = $row['gameSubTitle'];
}
} else {
// If the query failed, do something here
}
echo $gameLength;
?>
I see some people commenting that you need to put the $postId variable inside quotes in the query, but when using double-quotes (") variables will be posted, so it's not really needed. Also note that things are case-sensitive, so if your results doesn't show, check for spelling-mistakes.
There are many errors in your code
Try this...
<?php
$postId = 41;
?>
<!-- hidden items and variables. Elements that will not be revealed !-->
<span id="gameLength">
<?php
// MySQL connect configuration
$host = "localhost";
$dbname = "my_db";
$user = "username";
$password = "password";
$dbh = mysql_connect ($host,$user,$password) or die ('I cannot connect to the database because: ' . mysql_error() . '');
mysql_select_db($dbname, $dbh) or die('I cannot select the database because: ' . mysql_error());
$sql = "SELECT * FROM games WHERE postId='$postId'";
$result = mysql_query($sql);
while($rows = mysql_fetch_array($result)){
$gameId = $rows['id'];
$game100s = $rows['game100s'];
$gamesPlayedAllTime = $rows['gamesPlayed'];
$gamesPointsAllTime = $rows['gameScore'];
$gameLength = $rows['gameLength']; // get number of questions
$gameScore = $rows['gameScore'];
$gameType = $rows['gameType'];
$gametitle = $rows['gameSubTitle'];
echo $gameLength;
}
?>
You need to fix this is your code and that should fix the error.
$sql="SELECT * FROM games WHERE postId ='".$postId."' ";
If you want all the records you can use a while loop. Here is some pseudo code.
while($row = mysql_fect_assoc($query)){
echo $row["THE THING YOU WANT"];
...
}

PHP: connected to database, but mysql_query fails

I have very strange problem with PHP which I am starting to learn .. I have created tables in MySQL database with some data, and now I want to show them in webpage.
This is my source where I have this problem:
<?php
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
// I check the connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
// It always goes here
echo "Connected to database!";
}
// I am testing very simple SQL query.. there should be no problem
$result = mysql_query("SELECT * FROM cathegories", $con, $db);
if (!$result) {
// but it always dies
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($con);
?>
What is wrong?
Thanks in advance!
You are mixing mysql and mysqli.
Try something like:
<?php
$con= new mysqli("localhost","user","passwd","database");
if ($con->connect_errno){
echo "could not connect";
}
$select = "SELECT * FROM tablename";
if($result = $con->query($select)){
while($row = $result->fetch_object()){
echo $row->rowname."<br>";
}
}
else { echo 'no result'; }
$con->close();
?>
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $connection);
change to
// Here I open connection
$con = mysql_connect("localhost","root","aaaaaa");
// set the mysql database
$db = mysql_select_db("infs", $con);
mysql_query only takes two parameters - the actual SQL and then the link identifier (I assume in your case that's stored in $con; therefore remove $db from the third parameter).
You don't even need the second $con parameter really.
Where's the actual logic to connect to the database initially? Just because mysqli_connect_errno() doesn't return an error it doesn't mean the connection actually exists and that $con is available in the current scope.
I'd var_dump($con) before the mysql query to make sure it's a valid connection.

PHP - prepared statements and json_encode

I want to create a php script using prepared statements to query a table in my database and return the results in json format. I have a table of doctors and i want to return the doctors of a given speciality. I have a version of the script that doesn't use prepared statements that works fine. But when i use prepared statements my script doesn't work.
Non - prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality='$speciality'";
$result = $mysqli->query($query) or die("Error executing the query");
while($row = $result->fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$mysqli->close();
?>
prepared statements version:
<?php
// include database constants
require_once("../config/config.php");
// create db connection
$mysqli = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->set_charset("utf8");
$speciality = $_POST['speciality'];
$query = "SELECT * FROM `doctors` WHERE speciality=?";
if ($stmt = $mysqli -> prepare($query)){
$stmt -> bind_param("s", $speciality);
$stmt -> execute();
$result = $stmt -> get_result();
while($row = $result -> fetch_assoc()) {
$output[]= $row;
}
print(json_encode($output));
$stmt -> close();
} else {
echo $mysqli->error;
echo "no entry found";
}
$mysqli->close();
?>
What am i doing wrong? I don't get a mysqli error which means that the problem is after the execution of the query but i just don't know what it is.
Edit: What i mean by saying it doens't work is that i don't get anything back. The html body of the page after the execution is completely empty. On the other hand if i use the other script i posted (without prepared statements) i get the expected result.
UPDATED:
Use this:
/* bind result variables */
$stmt->bind_result($col1,$col2,$col3,$col4);
/* fetch values */
while ($stmt->fetch()) {
$output[]=array($col1,$col2,$col3,$col4);
}
Instead. Hope it helps.
anyone please give reason of putting downvote.
ini_set('display_errors',1);
error_reporting(E_ALL);
and then look at HTML body again. Most likely get_result is not supported but I hate to guess.
Make sure your version of PHP is compatible with the method
http://php.net/manual/pt_BR/mysqli-stmt.get-result.php
To get data as associative array you can do as follow:
$stmt->bind_result($col1, $col2);
$rows = [];
while ($stmt->fetch()) {
$rows[]=array("col1"=>$col1, "col2"=>$col2);
}

Wrong implementation of mysqli?

I am trying to use mysqli for the first time because i have some problems with multiple Query's in one php file. for start im just trying to retrieve data from the stored procedure and print it. but it looks like the code get's stuck somewhere it printed 'succesfull localhost' but it never get's to the code under it. The data never get printed neither the failed.
<?php
$link = mysqli_init();
if (!$link) {
die('mysqli_init failed');
}
if (!mysqli_options($link, MYSQLI_INIT_COMMAND, 'SET AUTOCOMMIT = 0')) {
die('Setting MYSQLI_INIT_COMMAND failed');
}
if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5)) {
die('Setting MYSQLI_OPT_CONNECT_TIMEOUT failed');
}
if (!mysqli_real_connect($link, 'localhost', 'root', '', 'fabiola')) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
echo 'Success... ' . mysqli_get_host_info($link) . "\n";
//require 'header.php';
$resID = mysqli_real_escape_string($_REQUEST['resID']);
$materialen_id = mysqli_real_escape_string($_REQUEST['materialen_id']);
$aantal = mysqli_real_escape_string($_REQUEST['aantal']);
$effectief_gebruikt = mysqli_real_escape_string($_REQUEST['effectief_gebruikt']);
$opmerking = mysqli_real_escape_string($_REQUEST['opmerking']);
$datum_van = $_REQUEST['datum_van'];
$datum_tot = $_REQUEST['datum_tot'];
$sqm = "CALL aantal_besch_mat_van_tot($datum_van,$datum_tot,$materialen_id,$resID)";
//$result = $mysqli->query($sqm) or die('Query Failed!');
/* Select queries return a resultset */
if ($result = $mysqli->query($sqm)) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* free result set */
mysqli_free_result($result);
}else{
echo 'failed';
}
mysqli_close($link);
?>
Where is $mysqli set or initialized?
There should be something like:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
but I can't see it.
btw it's weird that you're mixing the function calling convention 'mysqli_real_escape_string(...)' with the object-orientated functions '$mysqli->query(...)' I'm not sure it's safe to do both.
Also, you will save yourself a lot of heartache by using the MySQLi prepared statements rather than trying to make all your input safe by hand e.g.
$query = "CALL aantal_besch_mat_van_tot(?, ?, ?, ?);";
$statement = $mysqli->prepareStatement($query);
$statement->bind_param('iiii', $datum_van, $datum_tot, $materialen_id, $resID);
$statement->execute();
//get the results.
$statement->close();
$mysqli->close();
It's just so much easier, and more secure to use prepared statements (at the cost of a few percent of performance) that really you should almost always use them.

Categories