Ok so now I have this code where I'm retrieving data from db table:
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_row($query);
var_dump($row);
echo 'Connected successfully';
mysql_close($link);
?>
So in this table I have many rows and each has a "serial_number" column.... now what I'm trying to do is, get the row with the SPECIFIC serial_number (which I have as a variable)...
so for example
# serial_number
1 AB1
2 AB2
3 AB3
4 AB4
5 AB5
and for example I have a variable $product = AB2
How can I GET from the database only the row that has "serial_number" = $product=AB2 ?
Please can somebody help me with this. Thank you
Use MySQL WHERE Clauses like that :-
$query = mysql_query("select * from machine where serial_number = '$product'", $link);
Your Query work like that :-
select * from machine where serial_number = 'AB2'
Well it is actually not hard you just need to know what to do here. So as Rahautos said, you can use the WHERE clause.
Your code(fixed):
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine where serial_key='SERIAL KEY'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
?>
or instead you can use a form, input the key in the text field and get the results out with automation:
<?php
if(isset($_POST['submit']) {
$link = mysqli_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysqli_select_db("funkireport", $link);
$key = $_POST['key']
$query = mysql_query("select * from machine where serial_key='$key'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Key:</label>
<input type="text" name="key">
<input type="submit" name="submit">
</form>
Related
*The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.
I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?
The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:
<?php
$connect = mysql_connect('localhost', 'root');
if ($connect == false)
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
if ($select == false)
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>
NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".
The second way I tried:
<?php
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
$select = mysql_select_db('ViviansVacations');
{
die ("Unable to select database<br>");
}
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
?>
<select name="select1">
<?php
while ($line = mysql_fetch_array($result))
{
?>
<option value="<?php echo $line['Europe'];?>"> <?php echo
$line['field'];?> </option>
<?php
}
?>
</select>
This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:
"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database
"); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>
So there are many problems with your approach. First of all you are using a deprecated mysql_* functions which is bad idea and second you are not debugging your database connection properly :
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
In above code the die statement will always execute stopping further execution.
Also make sure the database ViviansVacations and table Destinations and column Europe exists with correct names(Follow standards and try to use all small letters for database/table/column naming)
The correct mysqli_* approach is(tested locally and the select box forms correctly) :
<?php
$db = 'ViviansVacations';
$mysqli = new mysqli('localhost', 'root', '', $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
$query = "SELECT * FROM Destinations";
$result = mysqli_query($mysqli, $query);
?>
<select name="select1">
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['Europe'] . "'>" . $row['Europe'] . "</option>";
}
?>
</select>
There are couple of things, you to verify and correct.
First of all, your database connection code, that doesn't seems to be correct. I didn't see any condition on which you are suppose to invoke die.
$connect = mysql_connect('localhost', 'root');
{
die ("Unable to connect to database<br>");
}
From the above code, below line will execute all the time
die ("Unable to connect to database<br>");
You should correct your database connection code to below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
You can refer mysql_connect for the usage.
Also, verify your file extension is .php
Mainly your problem is database connection. Try this -
<?php
mysql_connect("localhost", "root", "") or
die("Could not connect: " . mysql_error());
mysql_select_db("your_db");
$result = mysql_query("SELECT * FROM your_table");
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
echo "<br>";
}
mysql_free_result($result);
?>
There could be few issues:
Use mysqli_connect instead of mysql_connect because mysql is depreciated
Make 3rd parameter as empty `mysqli_connect('localhost', 'root', '');//as per standards
Debug your code for example: (print_r($connect), execute your query in phpmyadmin, print_r($result) and then in loop print_r($row).
At end, I am sure you will get your desired result and also you will know in detail that what was happening.
You might want to try to use this ..The dept_id and the description u have to change according to your database .Hope this will help you
<?php
$sql = mysql_query("SELECT dept_id ,description FROM department
ORDER BY dept_id ASC");
db_select($sql,"dept_id",$dept_id,"","-select Department-","","");
?>
I have been trying for the past while to echo out the result of a a MySQL query in PHP. I can't seem to get it to work so I am a bit lost. I know for a fact that the query works as I have done it in PHPMYADMIN and it is working fine, however whenever I load the webpage, nothing is outputted. For the purposes of this question I have generalized the things in the query as I obviously don't want anyone accessing my database. This is what I have tried:
<?php
$connect = mysql_connect('host', 'user', 'password', 'dbname');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('dbname')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT SUM(row name) FROM `table`');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($connect);
?>
I look forward to your replies.
mysql_result need the second parameter (The row number from the result that's being retrieved).
echo mysql_result($result, 0);
you have to change
echo mysql_result($result);
by
echo mysql_result($result,0);
or you can use
print_r(mysql_fetch_assoc($result));
Try this
echo mysql_result($result,0);
For more information, please give a look on http://www.php.net/mysql_result
or you can use mysql_fetch_row instead of mysql_result.
$row = mysql_fetch_row($result);
echo $row[0];
You may use this following format:
Give your Sql command like this:
$result = mysql_query('SELECT SUM(row name) as new_column_name FROM `table`');
then use this loop
while($fetched_values = mysql_fetch_array($result)){
echo $fetched_values['new_column'];
}
In your mysql_connect you have provided 4 parameters. it accepts 3 params
host, username and password. dbname is given inside mysql_select_db
as you can see from official docs. So remove the 4th param from mysql_connect function.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
http://php.net/function.mysql-connect
$db_selected = mysql_select_db('foo', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
but these mysql_* function will be deprecated use mysqli instead.
pass a row number as second parameter in mysql_result
echo mysql_result($result, 1);
or
use print_r(mysql_fetch_array($result));
where $result is your result resource
if you have any doubt you may refer my following example program.
<?php
$connect = mysql_connect('localhost', 'user_name', 'password', 'db_name');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name'))
{
die('Could not select database: ' . mysql_error());
}
$row = mysql_query('SELECT (Tamil+English+Maths) as total FROM table_name');
if (!$row)
{
die('Could not query:' . mysql_error());
}
while($fetched_row = mysql_fetch_array($row)){
echo $fetched_row['total'];
}
mysql_close($connect);
?>
here Tamil,English and Maths are the column values of my table
I have this code:
<?php
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
$result = mysql_query("SELECT SUM(colname) FROM profits");
$total = reset (mysql_fetch_assoc($result));
mysql_close($con);
echo $total;
?>
And its outputting an Resource id #5. Any help? Thanks in advance!
Don't use reset() like that - if you need a single value, just use list():
$result = mysql_query("SELECT SUM(colname) FROM profits");
list($total) = mysql_fetch_array($result);
reset() does not work as you expect on associative arrays: https://bugs.php.net/bug.php?id=38478
You're trying to echo an associative array with echo $total;. Instead just echo the first (and probably only based on your query) item.
$row = mysql_fetch_assoc($result);
echo $row[0];
I currently have this:
<?php
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
$query = "SELECT * FROM pages where id=1";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
See this part: SELECT * FROM pages where id=1
1 is the record id and it's currently hardcoded. What I need to do is change it so it get's the record id from the url...for example: mysite.com/index.php?2 would show record id 2 ...
How do I go about doing this?
Turn that hardcoded value into a variable.
<?php
//assumes you have a querystring like: http://mysite.com/index.php?id=3
$id = $_GET['id'];
$con = mysql_connect('localhost', 'root', 'dev');
if(!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("myDB");
//Make your variable safe for use with mysql
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM pages where id=" . $id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
let say the url is something like that: mysite.com/index.php?id=2
in your index.php:
<?php
$id = $_GET['id'];
// your sanitizing methods for id to avoid SQL injection
$con = mysql_connect('localhost', 'root', 'dev');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("diy");
$query = "SELECT * FROM pages where id = ".$id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$contents = $row['content'];
echo $contents;
?>
Beware of SQL injection
Basic example using mysite.com/index.php?id=x as your URLs where x is the Id:
$id = (int)$_GET['id'];
$query = sprintf("
SELECT *
FROM pages
WHERE id = %d",
mysql_real_escape_string($id)
);
With your connection lines included of course, you should also validate.
URL data is interpreted using the GET method. First, you should look here for how to use it, and here for how to read it.
Basically, your URL will look like this:
mysite.com/index.php?id=2
Then, you could read in the URL variable like this:
$id = mysql_real_escape_string($_GET['id']);
mysql_real_escape_string() will help avoid SQL injection, but requires an existing connection, so your code would look like this:
<?php
// Set up connection
$id = mysql_real_escape_string($_GET['id']);
$query = 'SELECT * FROM pages where id = '.$id;
// Run the query
?>
You could use a regular expression to extract it from the URL.
$retval=preg_match( "#(\d+)$#", $_SERVER['REQUEST_URI'], $match );
$index=-1;
if( $retval ) {
$index = $match[1];
}
This approach allows you to continue using the URL scheme you described in the question without prepending id=. Whether that's a good idea or not is probably debateable.
http://pastebin.com/NEZe7jjL
<?php
$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'user', 'password', array(
PDO::ATTR_EMULATE_PREPARES => true,
PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8',
));
$stmt = $dbh->prepare('SELECT * FROM `pages` WHERE `id` = :page');
$stmt->bindValue(':page', $_GET['page'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>
yoursite.com/index.php?page=2
I'm using jqueryui and its Autocomplete plugin. It use a json to extract items.
I want to modify it so that items will be extracted from my db.
Here is how items should be :
$items = array(
"Great <em>Bittern</em>"=>"Botaurus stellaris",
"Great2 <em>Bittern</em>"=>"Botaurus stellaris 2"
);
How to make an sql query that extract data from a table and write it like the code above into the php file ?
Table : customer
id_customer | name_customer | country_customer
I want that array produce id_customer => name_customer
The query is just:
SELECT id_customer, name_customer FROM customer
and you can generate the array like so (assuming you are using MySQL):
$items = array();
$result = mysql_query($sql);
while(($row = mysql_fetch_assoc($result))) {
$items[$row['id_customer']] = $row['name_customer'];
}
References: MySQL SELECT syntax, mysql_query(), mysql_fetch_assoc()
<?php
//Use mysql_connect for connect to a Db
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Select a DB
$db_selected = mysql_select_db('db_name', $link);
if (!$db_selected) {
die ('Can\'t use dbame_n : ' . mysql_error());
}
//Build a query
$sql = "SELECT id_customer, name_customer FROM customer";
//Send de query to db
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// Initialize Array
$arr_customers = array();
while(($row = mysql_fetch_assoc($result))) {
$arr_customers[$row['id_customer']] = $row['name_customer'];
}
// convert to JSON
$json = json_encode($arr_customers);
// Send to JqueryUI
echo $json;
exit();
?>