Return sql query as array - php

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();
?>

Related

get SPECIFIC database row with php

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>

Echoing MySQL query in PHP

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

Invalid query: Table doesn't exist

I am trying to insert data in table in mysql database through php code but I am always getting following error:
Invalid query: Table 'whatsup_wp1.pushDevices' doesn't exist
I am using following code:
<?php
$deviceid = $_GET["deviceid"];
$link = mysql_connect('localhost', 'whatsup_wp1', 'XSvUCl0FugzV4');
if (!$link) {
die('Not connected : ' . mysql_error());
}
// make foo the current db
$db_selected = mysql_select_db('whatsup_wp1', $link);
if (!$db_selected) {
echo 'Can\'t use whatsup_wp1 : ' . mysql_error();
}
else
{
//echo 'connect';
}
//$query = "select count(*) from city";
//$query = "insert into devices (pushID) values('".$deviceid."')";
$query = "INSERT INTO pushDevices(device) VALUES ('".$deviceid."')";
echo $query;
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
echo $result;
?>
This database have more tables and I am able to use them. I am having problem with the tables that I am creating today. They appears in phpmyadmin but somehow I am not able to get use them through my php code.
Any help may be vital for me. I have spent complete day on it.
Thanks
Pankaj
Its hard to tell by What your saying but i have a suggestion.... It looks like theres no table selected try this
it formatted like this
$query = "INSERT INTO mydb.mytable
(mytablefield)
VALUES
('myfieldvalue')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
My guess is you meant for it to be like this?
$query = "INSERT INTO whatsup_wp1.devices
(device)
VALUES
('".$deviceid."')"
$result = mysql_query($query);
if (!$result){
die('Invalid query: ' . mysql_error());
}
And for security reasons i recommend this...
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Change to
else
{
//echo 'connect';
$deviceid = mysql_real_escape_string(stripslashes($deviceid));
}
Personally i just use it like this
$result = mysql_query("INSERT INTO mytable
(mytablefield)
VALUES
('myfieldvalue')");
if($result){echo "Works!";}
else{die('Invalid query: ' . mysql_error());exit();}
If you are on Linux, check that the case is the same.
On windows MySql is case insensitive, on Linux, it is case sensitive.
Also, you are missing a space after pushDevice: pushDevice(...

While database loop in a foreach array loop. PHP/MYSQL

The below script works fine but only for the first record in the array.
$codes = array(1,2,3,4,5,6,7,8,9,10); // demo for this question, i actually have 1000+
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect1: ' . mysql_error());
}
$con2 = mysql_select_db("db", $con);
if (!$con2)
{
die('Could not connect2: ' . mysql_error());
}
$productsid = "select `products_id` from `coupons_products` where `coupons_id`=58386264";
$productsquery = mysql_query($productsid);
foreach ($codes as $code) {
while ($productid = mysql_fetch_assoc($productsquery)){
$sql = "insert into discount_coupons_to_products values (
'$code',
'{$productid['products_id']}')";
$con4 = mysql_query($sql);
if (!$con4)
{
die('Could not connect4: ' . mysql_error());
}
}
} // end foreach
I have an array of codes from the database that need apply only to specific products(same as 58386264). The codes works but only for the first coupon in the array ($codes).
If I understand what it means, you will need to run mysql_query command every step inside foreach, not just run mysql_fetch_assoc like you're actually doing.

Getting JSON From An External MySQL Database Error?

i am using this tutorial and i dont know what is error is this
<?php
header('Content-type: application/json'); // this is the magic that sets responseJSON
// Connecting, selecting database
$link = mysql_connect($dbhost, $dbuser, $dbpass)
or die('Could not connect: ' . mysql_error());
mysql_select_db($dbname) or die('Could not select database');
switch($_POST['op']) {
case 'getAllRecords': {
$table = $_POST['table'];
$query = sprintf("SELECT * FROM %s", mysql_real_escape_string($table));
// Performing SQL query
$result = mysql_query($query) or die('Query failed: ' . mysql_error());
$all_recs = array();
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
$all_recs[] = $line;
}
break;
}
}
echo json_encode($all_recs);
// Free resultset
mysql_free_result($result);
// Closing connection
mysql_close($link);
?>
error is :- null
Warning: mysql_free_result(): supplied argument is not a valid MySQL result resource in /home/ajay/public_html/mapleleafrealities.com/test.php on line 26
This is Example
My Error
if you have any simple example of getting json from external db please give me link or code
The op POST parameter is not "getAllRecords", so you're trying to encode something that doesn't exist, and free a result that was never taken. Try putting them inside.

Categories