Mysql parameterized queries in php - php

I have a php code for some MYSQL interogations,
Code is:
$DBTYPE = 'mysql';
$DBHOST = 'localhost';
$DBUSER = 'tuser';
$DBPASSWORD = 'password';
$DBNAME = 'dbname';
$link = mysql_connect($DBHOST, $DBUSER, $DBPASSWORD);
mysql_select_db($DBNAME);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//IMG**0**
$hotelc = $hotelCodes[**0**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**0** = $row["ImageURL"];
}
//IMG**1**
$hotelc = $hotelCodes[**1**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**1** = $row["ImageURL"];
}
..........................
//IMG**x**
$hotelc = $hotelCodes[**x**];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL**x** = $row["ImageURL"];
}
The repeating value on each code line is bolded.
How can i create a Mysql parameterized queries in php.n to avoid write all the lines .I need to extract ~100 $ImageURL from the Flat_table where the $hotelc is found.

For example you have to repeat it $N times:
for($i=0; $i<$N; $i++)
{
$hotelc = $hotelCodes[ $i ];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: ".mysql_error());
}
while ($row = mysql_fetch_array($result)) {
${'ImageURL'+$i} = $row["ImageURL"];
}
}

To loop, use for:
for($n=0; $n<100; $n++){
$hotelc = $hotelCodes[$n];
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode= '$hotelc'", $link);
if(!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
$ImageURL[$n] = $row["ImageURL"];
}
}
But the inner functions inside the loop is inefficient because mysql query will be executed 100 times. You can query all the ImageURL by using IN() syntax in mysql:
//Wrap all hotelCodes into one string for query, like ["a","b"] to "'a','b'"
$len = count($hotelCodes);
foreach($hotelCodes as $key=>$code){
$hotelCodes[$key] = "'".$code."'";
}
$codesStr = implode(",", $hotelCodes);
$result = mysql_query("SELECT ImageURL FROM Flat_table where HotelCode IN (".$codeStr.")", $link);
//Other things...

When writing a function, you look for the commonality. Furthermore, you want to minimize the database interaction. I am, for the sake of deprecation, going to assume $link uses mysqli_connect()
$ImageURL = array();
$list = implode('", "', $hotelCodes);
$result = mysqli_query($link, 'SELECT ImageURL FROM Flat_table where HotelCode IN "' . $list . '"');
while($row = mysql_fetch_assoc($result)) {
$ImageURL[] = $row["ImageURL"];
}
This runs only one query and then loops through the results, generating an associative array. So echo $ImageURL[0]; will output your first URL.

Related

Generating single JSON file for two tables

I am trying to create a single JSON file displaying data from two different tables. I can manage to fetch them, however I don't understand how to concatenate the two arrays. I am new to JSON. Any suggestions/tutorials would be very helpful. Thanks in advance.
Here the expected JSON:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
],
"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},
{"id":"3","image_1":"image3.jpg"}
]
}
but the JSON that I get is this:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
]},
{"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},{"id":"3","image_1":"image3.jpg"
}
]}
PHP code:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array();
$imageArray1 = array();
$imageArray["array1"] = array();
$imageArray1["array2"] = array();
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
array_push($imageArray["array1"], $tmp);
// $imageArray[] = $row;
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
array_push($imageArray1["array2"], $tmp);
// $imageArray[] = $row;
}
echo json_encode($imageArray);
echo ",";
echo json_encode($imageArray1);
//close the db connection
mysqli_close($connection);
?>
If you want the 2 sub arrays to belong to the same array then use only one array and address the 2 sub arrays like this when loading them
$imageArray["array1"][] = $tmp;
and
$imageArray["array2"][] = $tmp;
Amended code
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array(); // <- removed other arrays
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
$imageArray["array1"][] = $tmp; // <- address array like this
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
$imageArray["array2"][] = $tmp; // <- address array like this
}
echo json_encode($imageArray); // <- only one json_encode
//close the db connection
mysqli_close($connection);
?>
I would have done it this way using stdObject and selecting the specific data from the tables, and using mysqli_fetch_obect() so there is a lot less you have to do woman-draulically
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
// only select what you want
$sql = "select id,place_id,image from image_data";
$sql1 = "select id,image from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageObject = new stdObject();
while($row =mysqli_fetch_object($result))
{
$imageObject->array1[] = $row;
}
while($row =mysqli_fetch_object($result1))
{
$imageObject->array2[] = $row;
}
echo json_encode($imageObject);
?>

PHP reading fields in database

I have a script that reads my database table fields. Its not reading the first column which is the id.It reads the other fields and adds them into the array. I have added in the for loop a -1 to get every field but to no success.
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);
$key_values = array();
$link = mysql_connect($host,$user,$pass);
$db_select = mysql_select_db($dbselect);
$query = mysql_query('SHOW COLUMNS FROM '.$table.'');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = $dbselect;
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from '.$table.'', $link);
$num_fields = mysql_num_fields($res);
for($i=0;$i<$num_fields;$i++){
$key_values[]=mysql_field_name($res,$i);
}
echo "<pre>";
print_r($key_values);
echo "</pre>";
There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future.
<?php
$host=rtrim($_POST['host']);
$user=rtrim($_POST['user']);
$pass=rtrim($_POST['pass']);
$dbselect=rtrim($_POST['dbselect']);
$table=rtrim($_POST['table']);
$classname=rtrim($_POST['classname']);
$db = new mysqli($host,$user,$pass,$dbselect);
if($db->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
// NOTE real_escape_string may not work for tables untested
$result = $db->query("SELECT * FROM " . $db->real_escape_string($table));
if (!$result)
die "Error: " . $db->error;
while ($row = $result->fetch_object())
{
echo $row->id;
}
$result->close();
$db->close();
I don't see why it might be doing that, but this should be more reliable:
$query = mysql_query('select * from `%s`', mysql_real_escape_string($table), $link);
while ($result = mysql_fetch_array($query)) {
print_r(array_keys($result));
}
Try to use php native function mysql_fetch_array (also you need view this quastion before)
After try this code ($res === 'resources'):
$res = mysql_query('select * from '.$table.'', $link);
while ($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
$key_values[] = array_keys($row);
}
echo "<pre>";
print_r($key_values);
echo "</pre>";

How do I output certain index values from a foreach array?

This is the structure in the database:
items |itemLink
----------------------
Kill Bill|Kill Bill link
Preman |Preman link
This is the code:
$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
$items = 'SELECT items FROM menus';
$itemLink = 'SELECT itemLink FROM menus';
$itemQuery = $db->query($items);
$linkQuery = $db->query($itemLink);
$fetchItem = $itemQuery->fetchAll(PDO::FETCH_ASSOC);
$fetchLink = $linkQuery->fetchAll(PDO::FETCH_ASSOC);
$merged = array_merge($fetchItem,$fetchLink);
foreach($merged as $entry) {
foreach( $entry as $key => $value ) {
}
}
From the above code, how do I output only the items' datas?
Using the example above you could then do something like this to answer you question
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["FirstName"] . " " . $row["LastName"] . "<br>";
}
mysql_close($conn);
?>
I would use something like this, not two arrays for something that could be one query. I have shown three methods, using var_dump or print_r will show how each works.
$conn = mysql_connect($hostname, $username, $password);
if (!$conn) {
die('Could not connect to MySQL: ' . mysqli_connect_error());
}
$db_selected = mysql_select_db('sample', $conn);
if (!$db_selected) {
die("Can\t use db : ' . mysql_error()");
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
print_r($row);
}
$result = mysql_query('Select * from names');
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
print_r($row);
}
$result = mysql_query('Select * from names ');
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
print_r($row);
}
mysql_close($conn);

How can I create a json object in php

I am working in android and php.
I want to return a json object to android program from php program.
If these is a entry in a database then it is working properly. But when there is no record in database then it goes wrong.
I would welcome suggestions
I want to make json object like this ([{"id":"5"}])
This is my php program:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
//what should i right here to make jsonobject like this:- ([{"id":"5"}])
echo myjsono;
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
?>
How about something like this: (replace with your own variables)
if (empty($row)){
$arr = array('success' => 'false');
} else {
$arr = array('success' => 'true');
}
echo json_encode($arr);
If you want your android app to receive an object with a special id in the case of a not found condition I would return this:
{"id":"0"}
Then in your android app check if the id == 0 and that will tell you no records were found.
This is very correct solution for my question:-
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
if (mysql_num_rows($result)==0)
{
// {"messages":{"message":[{"id": "17","user": "Ryan Smith","text": "This is an example of JSON","time": "04:41"}]};}
**echo '('.'['.json_encode(array('id' => 0)).']'.')';** //**note this**
}
else
{
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
}
//mysql_close($con);
//echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>

Storing the result of an SQL call in a php variable

I have the code below and it's working as it should however instead of echoing the results to the screen, I need to store the results in a php variable called $var. How would I go about doing that?
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
while ($row = mysql_fetch_array($result)) {
echo $row['id_member'];
}
mysql_close($con);
?>
Depending on what you want to achieve here is a few possible ways of doing this
$var = "";
while ($row = mysql_fetch_array($result)) {
$var .= $row['id_member'] . "\n";
}
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
replace echo with $var[].
That will push each result onto the end of the array. It would probably be good to define the variable first.
$var = array();
while ($row = mysql_fetch_array($result)) {
$var[] = $row['id_member'];
}
<?php
$sql = "SELECT id_member FROM smf_members WHERE FIND_IN_SET(24,additional_groups)";
$con = mysql_connect('localhost', 'sqluser', 'sqlpass');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test_db");
$result = mysql_query($sql, $con);
$v = array(); // $v instead of $var, since var is a keyword and may cause troubles
while ($row = mysql_fetch_array($result)) {
array_push($v, $row['id_member']);
// or
//$v[] = $row['id_member'];
}
mysql_close($con);
?>
If the select statement will return more than one result, then you need to store the values in an array:
$member_ids = array();
while ($row = mysql_fetch_array($result)) {
$member_ids[] = $row['id_member'];
}
If the select statement will return a single result (you can make sure by appending a LIMIT 1 to the value of the $sql variable).
$row = mysql_fetch_array($result);
$member_id = $row['id_member'];

Categories