I am very new to PHP. I have been programming in PLSQL and .NET for a while. I have a tricky assignment since I lack PHP experience. n1, n2, n3 are all numeric values identifiers for employees. I want to call a function that looks up the employee by the number and return the employee name on the html page. In PLSQL I would create a function and call it but I am not sure how to do it here.
<?php
$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "dbname ";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function GetEmployee($nEmployee){
$result = mysql_query("SELECT szLastName FROM employee WHERE nEmployee =
$nEmployee ") or trigger_error(mysql_error());
return $result;
}
$sql = "SELECT idPosition, n1, n2, n3 FROM offense ORDER BY idPosition";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["idPosition"]."</td><td>".$row[$GetEmployee("n1")]."
</td>
<td>".$row[$GetEmployee("n2")]."</td><td>".$row[$GetEmployee("n3")]."</td>
</tr>";
}
} else {
echo "<tr><td>"%nbsp;"</td><td>"%nbsp;"</td><td>"%nbsp;"</td><td>"%nbsp;"
</td>
</tr>";
}
$conn->close();
?>
There are quite a few bugs in there.
You are using both mysql and mysqli ( mysql is deprecated and you should rather use PDO than mysqli, but if you wanna keep it, keep it with mysqli everywhere in your code ).
Instead of $row[$GetEmployee("n1")] you should use $row[GetEmployee("n1")]
Once you change your functions from mysql to mysqli you'll have to pass the connection variable and to access it inside your getemployee function you have to either make it global by declaring global $conn; inside your getemployee function or to pass it as parameter.
After setting those right, you'll probably stil get "Undefined offset: 0" error because you are trying to access an element of the array at a key that doesn't exist in your case.
Here it is fixed, but I might've missunderstood your table structure or expected output since you haven't provided any examples, but I'm confident you'll find what you need in it as it takes the n1, n2, n3 from offense and then pull szLastName for each one of them from employee:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
function getEmployee($nEmployee){
//Declare your global conn to be able to use it inside
//the function, HOWEVER, this is not recommendet.
global $conn;
$resultEmployee=mysqli_query($conn, "Select szLastName from employee WHERE nEmployee = $nEmployee");
while($row=mysqli_fetch_assoc($resultEmployee)){
return $row['szLastName'];
}
}
$resultNumbers = mysqli_query($conn, "SELECT idPosition, n1, n2, n3 FROM offense ORDER BY idPosition");
if($resultNumbers ->num_rows > 0){
while($row = mysqli_fetch_assoc($resultNumbers)){
echo "<tr><td>";
echo $row['idPosition'];
echo "</td>";
echo "<td>";
echo getEmployee($row['n1']);
echo "</td>";
echo "<br/>";
echo "<td>";
echo getEmployee($row['n2']);
echo "</td>";
echo "<br/>";
echo "<td>";
echo getEmployee($row['n3']);
echo "</td></tr>";
}
}
$conn->close();
?>
If you are new to PHP and want to continue, you should write your PHP to MySQL connections using PDO. (A very good source is: https://phpdelusions.net/pdo )
Also this is my first answer on StackOverflow, I hope you find it useful.
Related
I need some help and I can't figure it out,i tried searching the internet but I found nothing
So I'm using this code from w3schools
<?php
$servername = "localhost"; //Obviously this are set to my parameters
$username = "username"; //Obviously this are set to my parameters
$password = "password"; //Obviously this are set to my parameters
$dbname = "myDB"; //Obviously this are set to my parameters
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM People";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Some code goes here
}
} else {
echo "0 results";
}
$conn->close();
?>
How can I modify this code to echo certain items only?
EXAMPLE
I have 10 items in talbe People (Table people contains id,age,name,gender)
I want to echo out 3 out of 10 People by using their ID which are 1 trough 10
I know i can use this AND id IN(1, 5, 9)"; This just echoes them out 1 after another
Is there a way to echo out id 1 goes here , id 5 goes here and than id 9 goes there like in 3 different places with 3 different codes or something? is this even possible?
You could use:
class people
{
public function people()
{
$sql = $this->conn->prepare("SELECT * FROM `people`");
$sql->execute();
$result = $sql->fetch(PDO::FETCH_OBJ);
return $result;
}
}
then when you want certain information you could simply use in say index.php:
$fetch = new people();
$info = $fetch->people();
you can then run simple echo's such as $info->name or $info->id etc etc..
Depending on how you're searching for the user you could just add
WHERE `userid` = :id
$sql->bindParam(':id', $userid);
and add $userid into the people($userid)
But this will vary depending on how you're pulling out specific users.
use this code
<?php
//using PDO
try
{
$conn = new PDO('mysql:dbhost=myhost;dbname=mydbname;', 'user','pass');
}
catch (PDOException $e)
{
echo $e->getMessage();
}
$getId = $conn->query("
SELECT * FROM users
WHERE id = 1
AND id = 5
AND id = 9
");
while ($ids = $getId->fetch(PDO::FETCH_OBJ)
{
echo $getId->id . '<br>';
}
I'm having a little trouble tinkering with PHP and Oracle using OCI8 to connect. I've confirmed that i'm able to connect, but keep getting the below error:
PHP Fatal error: Call to a member function query() on resource ... on line 17.
Here's the code I have currently
<?php
$DB = '//DBGOESHERE:PORT/SIDHERE';
$DB_USER = '****';
$DB_PASS = '****';
$conn = oci_connect($DB_USER, $DB_PASS, $DB);
//check for errors
if (!$conn)
{
$e = oci_error();
print htmlentities($e['message']);
exit;
}
$sql = "select display_name, last_export_file, last_export_date from schema.ms_export where last_export_date > sysdate -1 order by last_export_date desc";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'display_name') . " | ";
echo oci_result($stid, 'last_export_file') . " | ";
echo oci_result($stid, 'last_export_date') . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Any help would be greatly appreciated! Technically I'm trying to get it to output into a pretty HTML table, but starting with cheap and dirty line breaks.
Thank you!
Ends up the above was correct and I hadn't synced the most recent version of the php file. Sorry for the trouble!
i want to store multiple data with comma separated in single column and get back data with the help of php in different different line
like in column view it will looks like this-- toothbrush-1234,glass-1234,
in up there 1234 is product id
i want to get this data in php with separated values each line with its all details.
like
<?php $sql="select product_name form products where product_id=1234" ?>
So is it possible to get data and separat it by - and , from single column.
You want to display your comma separated data into separate rows. You can try this.
<?
//Here is the complete example of your code by using MYSQLi Object Oriented:
$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 product_id,product_name form products where product_id=1234";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$yourData = array();
while($row = $result->fetch_assoc()) {
$yourData[$row['product_id']] = explode(",",$row['product_name']);
}
if(count($yourData) > 0){
foreach ($yourData as $key => $value) {
foreach ($value as $productname) {
echo "Product ID >> ".$key. " -- Product Name >> ".$productname;
}
}
}
}
else
{
echo "0 results";
}
$conn->close();
?>
Side Note: If you are using mysql_* in your application than i suggest you to use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7.
I am using eclipse editor. I am programming within vtiger 5.4. in my file config.inc.php the variable $default_charset is setted as
$default_charset = 'UTF-8';
I'm trying to make a sql query in mysql using the next variable
$sql = "select cod_dpto from vtiger_ubi where dpto='" . $dpto . "'";
When I print the variable $dpto I get "SAÑA", but the execution of the query mysql
$adb->query ( $sql );
doesn't work. But when I modify my query as:
$sql = "select cod_dpto from vtiger_ubi where dpto='SAÑA'";
the instruction
$adb->query ( $sql );
returns the values that I need.
Could you help me please, how can I convert my variable $dpto such that the sql query works well.
EDIT
I trying to make the query with the below code, without vtiger, and I get 0 results for thw two cases with variable and writing 'SAÑA'
$servername = "localhost";
$username = "root";
$password = "peru2006";
$dbname = "consuladoperurio_com_br_2";
$port = "3306";
// Create connection
$conn = new mysqli ( $servername, $username, $password, $dbname, $port );
// Check connection
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "select cod_dpto from vtiger_ubigeo where dpto='$dpto'";
echo $sql;
$result = $conn->query ( $sql );
if ($result->num_rows > 0) {
// output data of each row
while ( $row = $result->fetch_assoc () ) {
echo "id: " . $row ["cod_dpto"] "<br>";
}
} else {
echo "0 results";
}
$conn->close ();
Your Select statement looks like this:
$sql = "select cod_dpto from vtiger_ubi where dpto='".SAÑA."';
you'll probably want it to look like:
$sql = "select cod_dpto from vtiger_ubi where dpto='$dpto'";
Notice no concat operator, and the variable is only wrapped in single quotes.
When i run the following code it will return 100 users record from a table but when i increase the value of LIMIT from 100 to a greater number like 5000 then it will not return anything.i have total 6000 records in table. So how can i access different number of records like 2000, 3000 or even all 6000 records? kindly Guide what's wrong!
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die('Could not connect to db: ' . mysql_error());}
mysql_select_db("distributedsms",$db);
$result = mysql_query("select * from users LIMIT 100", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['user no'] = $row['sno'];
$row_array['mnc'] = $row['mnc'];
$row_array['mcc'] = $row['mcc'];
$row_array['lac'] = $row['lac'];
$row_array['cell id'] = $row['cell id'];
$row_array['lat'] = $row['lat'];
$row_array['lng'] = $row['lng'];
$row_array['address'] = $row['address'];//push the values in the array
array_push($json_response,$row_array);
$users = $json_response;}
$fp = fopen('users_data.json', 'w+');
fwrite($fp, json_encode($json_response));
fclose($fp);
echo json_encode($json_response);
?>
First, enable error reporting in your INI or Script:
<?php error_reporting(E_ALL);
ini_set('display_errors', 1);
This will help you if there is any error/warning in case of low memory allocation or similar.
To fetch all records, you shouldn't use LIMIT, remove LIMIT from your SQL.
i.e. select * from users
You should not use mysql_connect as it is deprecated. Use mysqli_connect instead. Also, I don't think you need to iterate so much, just choose what you want in your select statement.
UPDATE: another factor on why this might be happening can also be the returned information from the database, if you have apostrophes ' in your strings and you try to use json_encode, it will break, you would need to addslashes first.
Try the following, change your LIMIT as you wish, and let me know if you still have those errors:
<?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 sno,mnc,mcc,lac,cell_id,lat,lng,address FROM users LIMIT 100";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$response = array();
while ($row = $result->fetch_assoc()) {
foreach($row as $k => $str){
$row[$k] = addslashes($str);
}
array_push($response, $row);
}
echo json_encode($response);
} else {
echo "0 results";
}
$conn->close();
?>