Querying UserID from database - php

I've been trying for ages to figure this out, but I can't do it.
$sqluser = "--";
$sqlpass = "--";
$hostname = "localhost";
$clientuser = $_COOKIE['user'];
//connection to the database
$dbhandle = mysql_connect($hostname, $sqluser, $sqlpass)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("clhtechn_si1",$dbhandle)
or die("Could not select database!");
//execute the SQL query
$idfinder = mysql_query("SELECT id FROM `si_customers` WHERE username='$clientuser'") or die(mysql_error());
$clientid = mysql_fetch_assoc($idfinder);
$query = "SELECT invoice_id, date, SUM(total) as invoiceTotal
FROM si_invoices
LEFT JOIN si_invoice_items ON si_invoices.id = si_invoice_items.invoice_id
WHERE si_invoices.customer_id='$clientid'
GROUP BY invoice_id
ORDER BY invoice_id";
$result = mysql_query($query);
$row=0;
while ($record = mysql_fetch_assoc($result))
{
$class = 'd' . ($row % 2);
$inv_date=substr($record['date'], 0, -9);
$inv_total=$record['invoiceTotal'];
$invoice_total=number_format($inv_total, 2);
echo "<tr class=\"{$class}\">";
echo "<td valign='top'>{$inv_date}</td>";
echo "<td valign='top'>{$record['invoice_id']}</td>";
echo "<td valign='top'>$invoice_total</td>";
echo "<td><a href='invoices/Invoice_{$record['invoice_id']}.pdf' target='_blank'>";
echo "<img src='urlhere' width='17' height='17' alt='PDF File' border='0' /></a></td>";
echo "</tr>";
$row++;
}
//close the connection
mysql_close($dbhandle);
Here is how my customers table is aligned:
Link to picture.
What is wrong with my code, and what code can I use to fix it?
Help is appreciated.

$clientid is an array as mysql_fetch_assoc() returns this type.
$row = mysql_fetch_assoc($idfinder);
$clientid = $row['id'];
also, you need to format $clientuser properly before placing it in a query.
So, the full code would be
$user = mysql_real_escape_string($_COOKIE['user']);
$sql = "SELECT id FROM `si_customers` WHERE username='$user'";
$res = mysql_query($sql) or trigger_error(mysql_error());
$row = mysql_fetch_assoc($res);
$clientid = $row['id'];
To make it the way you want, you have to use some abstraction library
With which you will have your id in one line (it's actually 2 lines just for sake of readability)
$sql = "SELECT id FROM si_customers WHERE username=?s";
$clientid = $db->getOne($sql,$_COOKIE['user']);
Here you can see an example of such a Mysql abstraction library.

Related

SELECT 2 Identical databases to get 2 website orders on one list

I'm trying to connect two databases into a mysql query and it's also great!
After that, I try to find data on the order in the correct database to get meta_value from it.
But it mixes meta_value $ first name and sometimes duplicates them on the rows.
If I just conect 1 database, they will come out as they should
Anybody can see what goes wrong?
Url to example: https:// http://kundeservice.coalsmile.com/test4.php
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$v1 = "coalsmil_wp282";
$v2 = "coalsmil_wp111";
$v3 = "coalsmil_wp72";
$v4 = "coalsmil_wp193";
$v5 = "coalsmil_wp555";
$v6 = "coalsmil_wp366";
$v7 = "coalsmil_wp74";
$v8 = "coalsmil_wp721";
$v9 = "coalsmil_wp924";
$v10 = "coalsmil_wp253";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
//Here I connect to both databases
$query103 = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' UNION
SELECT * FROM `$v2`.`wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' order by post_date DESC ") or die(mysqli_error($conn));
?>
<br>
<h2>Database 3</h2>
<table style="width: 100%">
<tr>
<td>ID</td>
<td>??</td>
<td>??</td>
<td>??</td>
<td>??</td>
<td>??</td>
</tr>
<?php
while($row = mysqli_fetch_array($query103))
{
// Here I try to find what database the customer is on
$id2 = $row['ID'];
if($row['ID'] == ''){
echo "intet id";
}else {
$query = mysqli_query($conn, "SELECT * FROM `$v1`.`wpd2_posts` where ID = '$id2' ORDER BY id") or die(mysqli_error($conn));
if(mysqli_num_rows($query) == '') {
$query = mysqli_query($conn, "SELECT * FROM `$v2`.`wpd2_posts` where ID = '$id2' ORDER BY id") or die(mysqli_error($conn));
if(mysqli_num_rows($query) == '') {
}else{
$version = "coalsmil_wp111";
}
}else{
$version = "coalsmil_wp282";
}
}
echo "<tr>";
echo "<td>". $row['ID']."</td>";
echo "<td>". $row['post_date']."</td>";
echo "<td>". $row['post_status']."</td>";
//And here I try to get the data out
$querynavn = mysqli_query($conn, "SELECT meta_value FROM `$version`.`wpd2_postmeta` where meta_key='_shipping_first_name' and post_id='$id2' ") or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($querynavn))
{
$fornavn = urldecode($row2['meta_value']);
}
echo "<td>". $fornavn."</td>";
echo "<td>".$version."</td>";
echo "<td>6</td>";
echo "</tr>";
}
?>
</table>
If you're connections are on the same database server you can specify the schema (database name) to select things from both over one connection. You do this by using schema_name.table_name instead of just the table's name.
So like:
SELECT * FROM schema_name.wpd2_posts WHERE ...
In your case you could use UNION to put it all together:
SELECT * FROM `schema1.wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' UNION
SELECT * FROM `schema2.wpd2_posts`
where post_status='wc-processing' or post_status='wc-completed'
or post_status='wc-failed' order by post_date DESC LIMIT 10
On a side note you could make this query a bit more readable by using the IN() clause for your critera:
WHERE post_status IN('wc-processing', 'wc-completed','wc-failed')

Take a single value from a MySQL field and store it in a variable

I am a beginner to PHP and MySql. What I wish to do is take a single field value from a MySql table and store it into a php variable. I tried this code but it does not seem to work:
//Get Role ID
$con= mysqli_connect("localhost","root","","darrenvellaedp2");
$result = mysqli_query($con,"SELECT userRoleID FROM tbl_users");
while($row = mysqli_fetch_array($result)) {
echo $row['userRoleID'];
echo "<br>";
}
//make the connection
$con = mysqli_connect("localhost","root","","darrenvellaedp2") or die("Error: " . mysqli_error($con));
//create the query
$result = "SELECT userRoleID FROM tbl_users" or die("Error: " . mysqli_error($con));
//execute the query
$res = $con->query($result);
while($row = mysqli_fetch_array($res)) {
//this will print the userroleid out to the screen
echo $row['userRoleID'];
//this will store it in a variable
$UserRoleID = $row['userRoleID'];
}
It would have been easier for you to just google it as there's a whole section about this on PHP.NET

SELECT * FROM Table Where ID

I am trying to retrieve information from my database depending on the ID a user types into my URL.
For example: If USER A went to www.exampleurl.com/index.php?id=1 it would echo out the user's information which has an ID of 1. Same thing if the id was 2, 3, etc. Users are entering their information via a form in a different file called submit.php.
Here is my code to retrieve data depending on ID :
<?php
$id = $_GET['id'];
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
echo "Hello, " . $result['name'];
?>
Any ideas on if my SELECT request is wrong?
EDIT
Here is my code for showing the data altogether in a table. This works fine.
<?php
//Variables for connecting to your database.
$hostname = "";
$username = "";
$dbname = "";
$password = "!";
$usertable = "";
//Connecting to your database
$con = mysql_connect($hostname, $username, $password) OR DIE ("Unable to
connect to database! Please try again later.");
mysql_select_db($dbname, $con);
//Fetching from your database table.
$query = "SELECT * FROM $usertable";
$result = mysql_query($query, $con);
echo "<table border=1>
<tr>
<th> ID </th>
<th> Name </th>
<th> Age </th>
</tr>";
while($record = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $record['id'] . "</td>";
echo "<td>" . $record['name'] . "</td>";
echo "<td>" . $record['age'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
→ Try This:
You should consider using PHP PDO as it is safer and a more object oriented approach:
$usertable = "";
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME', 'DB_USER_NAME', 'DB_USER_PASS' );
$statement = $database->prepare('SELECT * FROM $usertable');
$statement->execute();
$count = $statement->rowCount();
if( $count > 0 ) {
$R = $statement->fetchAll( PDO::FETCH_ASSOC );
for( $x = 0; $x < count($R); $x++ ) {
echo "<tr>";
echo "<td>" . $R[ $x ]['id'] . "</td>";
echo "<td>" . $R[ $x ]['name'] . "</td>";
echo "<td>" . $R[ $x ]['age'] . "</td>";
echo "</tr>";
}
}
else { echo "Error!"; }
you need to use mysql_fetch_assoc function for retrieve the results.
$result = mysql_fetch_assoc(mysql_query($query, $con));
echo "Hello, " . $result['name'];
You should be error checking your mysql_querys:
$query = "SELECT * FROM $usertable WHERE id = $id LIMIT 1";
$result = mysql_query($query, $con);
if(!result)
echo mysql_error();
You should also retrieve the results:
$array = mysql_fetch_assoc($result);
I'll consider some secure features like
Check if $_GET['id'] is set and if is int
Apply Mysql escape with mysql_escape_string() function

MySQL insert row from HTML table into db table

I am using a for loop to construct a HTML table from the contents of a MySQL table select query. I have a link on the end of each row to copy that row into another table.
I'm unsure how to get the data from the table row for the MySQL insert query - I have marked the place where I'm struggling with XXX.
<?php
mysql_select_db("cardatabase");
$link = mysql_connect("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query($query);
if($_GET['rent']) {
$rent = "INSERT INTO rentedcars VALUES('XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr><td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td></tr>";
for ($i = 0; $i < mysql_num_rows($result); $i++) {
$row = mysql_fetch_object($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
edit (updated code):
<?php
mysql_select_db ("cardatabase");
$link = mysql_connect ("localhost", "root", "password");
$query = "SELECT * from cars";
$result = mysql_query ($query);
if($_GET['rent']) {
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']);
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt);
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
echo "<table>";
echo "<tr>";
echo "<td>ID</td><td>Make</td><td>Model</td><td>Fuel Type</td><td>Transmission</td><td>Engine Size</td><td>Doors</td><td>Amount</td><td>Available</td><td>Date Added</td><td>Remove</td>";
echo "</tr>";
while ($row = mysql_fetch_object($result)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
echo "</table>";
mysql_* is deprecated as of PHP 5.5.0, you should use something like PDO.
try {
$DBH = new PDO('mysql:dbname=cardatabase;host=localhost', 'root', 'password');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$STH = $DBH->query("SELECT * FROM cars")->execute();
while ($row = $STH->fetch(PDO::FETCH_OBJ)) {
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=".$row->ID."'>Rent</a></td>
</tr>";
}
Edit: Just like #Skatox said!
I would do it like this:
<?php
$link = mysql_connect ("localhost", "root", "password");
mysql_select_db ("cardatabase");
$query = "SELECT * from cars";
$result = mysql_query ($query);
Get car information and store it
if($_GET['rent'])
{
$query_car = sprintf("SELECT * from cars WHERE ID=%s",$_GET['rent']); //Avoids sql injection
$rslt = mysql_query($query_car);
$car = mysql_fetch_object ($rslt)
Here you need to validate if there's no car
$rent = "INSERT INTO rentedcars VALUES('$car->ID','$car->CARMAKE','$car->CARMODEL','$car->FUELTYPE','$car->TRANSMISSION','$car->ENGINESIZE','$car->DOORS','$car->AMOUNT','$car->AVAILABLE','$car->DATEADDED')";
mysql_query($rent);
echo "<meta http-equiv='refresh' content='0;url=rent.php'/>";
}
Change it to while like #Vinoth Babu said:
while ($row = mysql_fetch_object ($result))
{
$row = mysql_fetch_object ($result);
echo "<tr>
<td>$row->ID</td>
<td>$row->CARMAKE</td>
<td>$row->CARMODEL</td>
<td>$row->FUELTYPE</td>
<td>$row->TRANSMISSION</td>
<td>$row->ENGINESIZE</td>
<td>$row->DOORS</td>
<td>$row->AMOUNT</td>
<td>$row->AVAILABLE</td>
<td>$row->DATEADDED</td>
<td><a href='?rent=$row->ID'>Rent</a></td>
</tr>";
}
print "</table>";
?>
I would recommend you to switch to MySQL PDO, it's safer and you'll get a better and secure code.
you are missing the column names in your insert query
$rent = "INSERT INTO rentedcars (id ,carmake, carmodel,fueltype,transmission, enginesize,doors,amount ,available, dateadded)
VALUES('xxx','xxx','".$carmodel."','XXX','XXX','XXX','XXX','XXX','XXX','XXX')";
^^^^^-------------i showed u exempel under
those XXX are values you get the from the inputs values
exemple
<input name= "car_model" id= "car_model" value="mercedes" >
then you get this value
if (isset($_POST['car_model'])){ $carmodel = $_POST['car_model']}
and then use this value $carmodel in your sql

display all data from my User table in my database

My question is how to display all data from my users table in my database?
I have this.
$loop = mysql_query(“SHOW users FROM $dbname”) or die (‘cannot select tables’);
You want to SELECT the users, not SHOW them.
Basic SQL loop example:
$sql = mysql_query("SELECT * FROM `users`");
while ($row = mysql_fetch_object($sql)) {
echo $row->id . ' ' . $row->nickname . '<br />';
}
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$result = mysql_query(“SELECT * FROM Users”, $link) or die (‘cannot select tables’);
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
mysql_free_result($result);
$loop = mysql_query('SELECT * FROM `users`') or die();
You don't want your database name to be in the query, and you want to be using SELECT
If you haven't connected to the database earlier then you need to add this before your query:
mysql_connect($mysql_host, $mysql_user, $user_password);

Categories