How to select one cell through the selected id. SQL - php

I have a database table in which there are 2 columns. The first is the ID, the second is the price. When the user selects a product on the site, a product card is opened (this will be id). At the bottom there is a calculator with prices where you need to load the price from the second column. Question: how to make a request for a specific ID(for loading price from second column). Here's the code that I could do.This code displays all IDs and prices, but need only when you select the product and only for it. Any help. Thank you
<?php
ini_set('display_errors','On');
error_reporting('E_ALL');//error's show
$host = 'localhost'; // host name
$database = 'test_sql'; // database name
$user = 'root'; // user name
$pswd = ''; // password
$dbh = mysql_connect($host, $user, $pswd) or die("Could not to connect MySQL.");//connect to mySQL
mysql_select_db($database) or die("Could not to connect database.");
$query = "SELECT * FROM `oc_product`";//load from product table
$res = mysql_query($query);
$row = mysql_fetch_array($res);//array call
while($row = mysql_fetch_array($res)){
echo "ID: ".$row['product_id']."<br>";//output for each ID
echo "Цена: ".$row['price']."<br>";//output for each price
}
?>

when you select a product pass that id to the function and update your query like :
$dbh = mysql_connect($host, $user, $pswd) or die("Could not to connect MySQL.");//connect to mySQL
mysql_select_db($database) or die("Could not to connect database.");
$query = "SELECT * FROM `oc_product` WHERE 'product_id' = <id that you passed>";//load from product table
$res = mysql_query($query);
$row = mysql_fetch_array($res);

Related

How to display results from a database from newest to oldest

I have a page that displays entered data from a database in a table. I am wondering how I can reverse the order displayed from newest to oldest.
Here is the code for the fetch page that displays my results in the table, html has been removed as it is irrelevant to the question.
<?php
// Create connection in mysqli
$connection = new mysqli($server, $user, $pass, $dbname);
//Check connection in mysqli
if($connection->connect_error) {
die("Error on connection:" .$connection->connect_error);
}
//Display the informaion
$sql = "SELECT * FROM logs";
$res = $connection->query($sql);
if($res->num_rows > 0) {
// echo table row code
while($row = $res->fetch_assoc()) {
// echo table row code
}
}
else {
echo "No Record Found!";
}
$connection->close();
?>
Simply modify your query like this :
$sql = "SELECT * FROM logs ORDER BY `column` DESC";
Where column is your column with the primary key. Normaly it is ID or id...

Returning the search query of the entire table

I have set the task before me to use PHP in doing the following work on MySQL table:
Take the search input from HTML form and put it in the $POST['search']
Select table data
Number the table rows and put the number of rows into variable
Take the first value from the first row and check if it is equal to $POST['search']. If it is, print it together with the column name.
Take the n-th value from the first row and check if it is equal to $POST['search']. If it is, print it together with the column name.
Repeat that for each row of the table
I solved the HTML form, database connection, select table data and numbering the table rows (1,2 and 3)
I need help with 4 and 5.
Here is the code so far:
// 1 Izvuci podatke iz tabele
$db_host = '';
$db_user = '';
$db_pwd = '';
$database = '';
$table = '';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
// count the rows
$row_num= mysql_query("SELECT COUNT(*) FROM {$table}");
Can someone help me continue ?
Thank you.

php mysql query with multiple conditions

I need the mysql query to get the items whose nid > 910 for user_id=1 and nid > 902 for used_id <> 1.
Anybody done this? Searched but cant find it, since i am new to php and mysql.
Can't you use OR in your WHERE criteria:
SELECT *
FROM YourTable
WHERE (nid > 910 AND user_id = 1)
OR (nid > 902 AND user_id <> 1)
Try with this query:
SELECT * FROM items WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1)
SQL Query:
SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);
But if you want to call it from PHP you'll need something like this:
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("exampledb",$dbhandle)
or die("Could not select exampledb");
//execute the SQL query and return records
$result = mysql_query("SELECT * FROM table_name WHERE (nid>910 AND user_id=1) OR (nid>902 and user_id!=1);");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'user_id'}." Nid:".$row{'nid'}."<br />";
}
?>

php/mysql: get data from one table, convert and insert in another table

Ok I will try to explain, (I am Portuguese lol).
I have a Database where I have the fallowing MySQL:
Database: ad
Table: notebooks
Fields: ID, tag, so, lastlogon, lastlogh
My ldap query gets data from ldap server (active directory) and stores it in my MySQL database (ad/notebooks).
I get tag which is tag number is unique.
I get so which is the OS installed in the notebook.
I get lastlogh which is the last logon time stamp, and it is unique too.
ID field is auto increment and key but I can set the tag filed to be key.
I have a config_notebooks.php where I set all the variables to connect to ldap and MySQL servers.
<?php
/*------------------------------------------------------------------------*/
//setting your variables
/*------------------------------------------------------------------------*/
//ldap host
$host = "ldap://HEICPT1VIA01.HEIWAY.NET";
//ldap user
$user = "domain\user";
//ldap password
$pswd = "pssw";
//ldap base structure
$dn = "OU=NotebookM2,OU=WorkstationsM2,OU=PT1,DC=heiway,DC=net";;
//attributs to search and get
$attrs = array("cn","operatingsystem","lastlogon");
//sql host
$sqlhost="localhost";
//sql user
$sqluser="root";
//sql password
$sqlpswd="";
//sql database
$database="ad";
//sql table
$table="notebooks";
?>
Now the query script
<?php
/*------------------------------------------------------------------------*/
//Query script
/*------------------------------------------------------------------------*/
include 'config_notebooks.php';
$filter = $_POST['filter']."=".$_POST['keyword']."*";
//connect to db
$con = mysql_connect("$sqlhost","$sqluser","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//connect to active directory
$ad = ldap_connect($host)
or die( "Could not connect!" );
// Set version number
ldap_set_option($ad, LDAP_OPT_PROTOCOL_VERSION, 3)
or die ("Could not set ldap protocol");
// Binding to ldap server
$bd = ldap_bind($ad, $user, $pswd)
or die ("Could not bind");
$search = ldap_search($ad, $dn, $filter, $attrs)
or die ("ldap search failed");
$entries = ldap_get_entries($ad, $search);
$sel = mysql_select_db("ad", $con);
if (!$sel)
{
die('Could not select DB: ' . mysql_error());
}
for ($i=0; $i<$entries["count"]; $i++)
{
$tag = $entries[$i]["cn"][0];
$so = $entries[$i]["operatingsystem"][0];
$lastl = $entries[$i]["lastlogon"][0];
mysql_query("
INSERT INTO
$table (tag, so, lastlogh)
VALUES
('$tag', '$so', '$lastl')
ON DUPLICATE KEY UPDATE
tag='$tag',
so='$so',
lastlogon='$lastl'
");
}
mysql_close($con);
ldap_unbind($ad);
if ($entries["count"] > 0)
header("Location: notebooks_list.php")
?>
In this query the last logon timestamp is coded like 130276262860634000
So I can export everything to excel and decode it, but I found a code that does that, so it saves time.
I created a new field in the database (lastlogon) and I need to fetch the data from lastlogh field, decode with the new script and store it in the lastlogon field.
This is the script that I found:
<?php
function adConvert ($ad) {
$seconds_ad = $ad / (10000000);
//86400 -- seconds in 1 day
$unix = ((1970-1601) * 365 - 3 + round((1970-1601)/4) ) * 86400;
$timestamp = $seconds_ad - $unix;
$normalDate = date("F d, Y", $timestamp);
return $normalDate;
}
//example: echo adConvert($ad);
?>
Using Mysql API
$res = mysql_query("SELECT * FROM $table");
while($row = mysql_fetch_assoc($res)) {
$logon_ts = adConvert($row['lastlogh']);
mysql_query("UPDATE $table SET lastlogon = '$logon_ts' WHERE tag='$row[tag]'");
}
I hope this solves your problem.
Note: Mysql API is deprecated as of PHP 5.5.0. So, It's highly recommended to use Mysqli API for newer developments.
man.. use the distinct for resolve u problem http://www.w3schools.com/sql/sql_distinct.asp

Field not being inserted into mysql database from php

I have a little problem where a field is not being inserted into my users table. I have two tables as follows:
users - id, gamerid, email, password, country, country_code
countries - country_id, country, country_code
Now i have a signup form that comprises of gamerid,email,password and a country select (pulls from the countries table using php)
My problem is that when i submit the form, i want to run a query to pull the country code from the table which matches what was selected by the user and insert these fields into the users table. All my data is inserting correctly except for the country_code.
Here is my code for the html select section:
<select name = "country_create" style = "height: 25px; width: 180px;">
<option value="0" selected="selected" class = "signup_form_country_select_class">Select your country</option>
<?php
include "config.php";
$connection = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($dbname, $connection) or die(mysql_error());
$result = mysql_query('SELECT country FROM countries');
while($row = mysql_fetch_array($result))
{
echo '<option value="'.$row['country'].'">'.$row['country'].'</option>';
}
?>
</select>
And here is the php from the register script:
$connection = mysql_connect($host, $username, $password) or die(mysql_error());
mysql_select_db($dbname, $connection) or die(mysql_error());
// INPUT CLEANING FUNCTION
function clean($str)
{
$cleaned = mysql_real_escape_string(strip_tags($str));
return $cleaned;
}
$gamerid = clean($_POST['gamerid_create']);
$email = clean($_POST['email_create']);
$password = clean($_POST['password_create']);
$country = ($_POST['country_create']);
$cc_qry = "SELECT country_code FROM countries WHERE country = '$country'";
$country_code = mysql_query($cc_qry);
$insert = "insert into users(gamerid,email,password,country,country_code) values('$gamerid','$email','$password','$country','$country_code')";
mysql_query($insert, $connection);
Thanks in advance guys!
First - use PDO or mysqli functions, but secondly - you must also fetch data from query result:
$res = mysql_query($cc_qry);
$res_cc = mysql_fetch_assoc($res);
$country_code = $res_cc['country_code'];

Categories