Return result of an mysql function - php

I have installed this Levenshtein function in MYSQL. The maker advises to use this:
select levenshtein('butt', 'but') from test;
select levenshtein_ratio('butt', 'but') from test;
I want to calculate the Levenshtein Ratio between $search and each "name" entry in the DB and then echo it in PHP.
How can I accomplish that? Thanks in advance
$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, ??? FROM names"; // What's the MYSQL I need to use?
$response = #mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($response)){
echo "Levenshtein Ratio: ".$row['???'];
echo "<br>";
}

You need to use an alias the function return
SELECT levenshtein('butt', 'but') as levenshtein FROM
then it can be accessed from the levenshtein index.
$row['levenshtein']
Also note:
In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.
So if you didn't want the alias you could do:
$row[1]
this is less readable/maintainable to me though.
When in doubt about what an array contains you can check it with print_r or var_dump. Those will give you the indices and the values the array has.

How about this ?
<?php
$search = "Paul"; // The string I want compared to each DB entry
$query = "SELECT name, levenshtein(name, '".mysqli_real_escape_string ($dbc, $search)."') AS result FROM names";
$result = #mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
echo "Levenshtein Ratio for ".$row['name'].' : '.$row['result']."<br />";
}

Related

How to extract string value of array from database?

I have this text string varchar type i get from database echo.
how to extract it and count the value :
in the database it save as string ["1","2","3"] in varchar.
how to count this as 3 item using php?
my sql code is :
$sql2 = "SELECT * FROM il_dcl_stloc1_value WHERE record_field_id = '$exc_prt_id'";
$result2 = $conn->query($sql2);
while($row2 = $result2->fetch_assoc()) {
$exc_prt_id1 = $row2['value'];
echo "$exc_prt_id1"; // this will result ["1","2","3"]
}
There are tons of ways you can do this, but if you just care about the count, not the values, and they will always come in this format, you can just use
$count = count(explode(",", $exc_prt_id1));
You can also do a
$count = count(json_decode($exc_prt_id1));
If you want the values, run the above code without the count.
$arr = json_decode($exc_prt_id1);
This will result in a PHP array.
While the 2nd option is generally preferred and is better practice, the 1st one might be of use in certain cases. If there is anything unclear, just ask :)
Try this way
$exc_prt_id1= str_replace("[","",$exc_prt_id1);
$exc_prt_id1= str_replace("]","",$exc_prt_id1);
$exc_prt_id1= str_replace('"','',$exc_prt_id1);
$invoiceArr = explode(",",$exc_prt_id1);
$count = count(explode(",", $invoiceArr ));

mysql_fetch_array doesn't render the expect values of the SQL query

In the phpMyAdmin interface I run the following SQL query:
SELECT id FROM table WHERE family = '1' AND type = 'B1'
and receive the following results:
'1', '18546269', '51534064' which are correct.
Then I wrote the following code in PHP:
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysql_query($query);
$array = mysql_fetch_array($result);
echo '(', implode(',',$array) ,')';
But receive the following result:
(1,1) which I didn't expected.
I thought that (1,18546269,51534064) would be displayed.
Then I wrote the following code to verify what should be displayed:
print_r ($array);
and was very surprised that the values were:
Array ( [0] => 1 [id] => 1 ).
In the end I wrote:
while($array = mysql_fetch_array($result)) {
echo $array['id'],',';
}
and as expected received exactly this:
1,18546269,51534064,
which I can't use because I need a string exactly like that: (1,18546269,51534064).
In fact I 'just' need a variable that gives me the same values of the SQL query that I run in phpMyAdmin.
I'm really confused and would be great if one of you guys could help me.
Solutions with mysqli would be appreciated as well. :-)
$query = "SELECT id FROM table WHERE family = '1' AND type = 'B1'";
$result = mysqli_query($link, $query);
$ids = '';
while($row = mysqli_fetch_array($result)) $ids .= $row['id'].',';
// Filter the text a bit
$ids = rtrim($string, ',');
$ids = '('.$ids.')';
echo $ids;
You basically initiate a variable, put all the ids in it, remove the last comma, append the brackets and that's it.
As documented under mysql_fetch_array():
Return Values
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. The type of returned array depends on how result_type is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.
[ deletia ]
Example #2 mysql_fetch_array() with MYSQL_NUM
<?php
mysql_connect("localhost", "mysql_user", "mysql_password") or
die("Could not connect: " . mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT id, name FROM mytable");
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %s Name: %s", $row[0], $row[1]);
}
mysql_free_result($result);
?>
That is to say, the function returns only one row, by default as an array consisting of both associative and numeric-indexed columns from the resultset. You want instead make multiple calls to the function, with a suitable result_type parameter (as shown above).
mysql_fetch_array fetches array of row, not array of column. That means, if you would have ID and name, the fetched array would contain on each row an id and a name.
Quite a simple modification of your code that should fix the problem would be
$i=0;
$data=array();
while($array = mysql_fetch_array($result)) {
$data[$i]=$array['id'];
$i++;
}
echo '(', implode(',',$data) ,')';

Extract a specific value from this data type

I'm using this script to get data from a database
$sql = "SELECT * FROM items WHERE catid = 1";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
echo $row['extra_fields'];
}
The output is:
[{"id":"1","value":"johndoe"},{"id":"2","value":"marydoe"}]
I want to extract/print only the value corresponding to "id":"1" (that in this case is 'johndoe'). I'm not able to extract it from the above data type.
To read JSON in PHP use
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields'];
// Do something with $array['id']
}
Did you realise you can directly go for that data in MySQL?
SELECT value FROM items WHERE id = 2;
edit:
Basically your query is
SELECT comma-separated column names or star for all, use only what you really need to save bandwidth, e.g. SELECT id, value
FROM table-name, e.g. FROM mytable
WHERE columnname = desired value, e.g. WHERE id = 2
You want to query only the required columns in the required rows. Imagine one day you would have to parse 1 million users every time you want to get an id... :)
The output is JSON. Use PHP's json_decode function.
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
foreach($array AS $item) {
echo $item['id'];
}
}
Currently this is the code that fits my needs:
while($row = mysql_fetch_array($result)){
$array = json_decode($row['extra_fields']);
$value = $array[0]->value;
}
You should do it in the mysql query part. For example, set the ID = 1 in the query.

Echo the results of query based on its index

This is pretty basic but I can't seem to get it to work
I have this query
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$row_people = mysql_fetch_assoc($people);
$totalRows_people = mysql_num_rows($people);
I can echo the first result of this query with
<?php echo $row_people['name']; ?>
I could also create a loop and echo all the results.
But I really want to echo the results individually based on its index.
I have tried this, but it does not work.
<?php echo $row_people['name'][2]; ?>
Thanks for your help.
You can fetch them by their index using a WHERE clause.
$people = sprintf("SELECT name FROM people WHERE index='%d'", $index);
If you want to query all rows, you could store them into an array while looping over them:
$people = "SELECT name FROM people";
$people = mysql_query($people) or die(mysql_error());
$totalRows_people = mysql_num_rows($people);
$rows_people = array();
while($row_people = mysql_fetch_assoc($people))
{
$rows_people[] = $row_people;
}
You might want to add the primary key to the returned fields and use it as the array index probably.
You can ORDER them by their index and then use a loop.
$people = "SELECT name FROM people ORDER by index";
You can use mysql_data_seek on the result object to seek to a particular row. E.g., to get the name value from row 2:
mysql_data_seek($people, 2);
$row_people = mysql_fetch_assoc($people);
echo $row_people['name'];
If you're doing this a lot it will be easier to gather all the rows together in a single array at the start:
$data = array();
while ($row = mysql_fetch_assoc($people)) $data[] = $row;
This way you can fetch any cells in the results trivially:
echo $data[2]['name'];

Get rows from mysql table to php arrays

How can i get every row of a mysql table and put it in a php array? Do i need a multidimensional array for this? The purpose of all this is to display some points on a google map later on.
You need to get all the data that you want from the table. Something like this would work:
$SQLCommand = "SELECT someFieldName FROM yourTableName";
This line goes into your table and gets the data in 'someFieldName' from your table. You can add more field names where 'someFieldName' if you want to get more than one column.
$result = mysql_query($SQLCommand); // This line executes the MySQL query that you typed above
$yourArray = array(); // make a new array to hold all your data
$index = 0;
while($row = mysql_fetch_assoc($result)){ // loop to store the data in an associative array.
$yourArray[$index] = $row;
$index++;
}
The above loop goes through each row and stores it as an element in the new array you had made. Then you can do whatever you want with that info, like print it out to the screen:
echo $row[theRowYouWant][someFieldName];
So if $theRowYouWant is equal to 4, it would be the data(in this case, 'someFieldName') from the 5th row(remember, rows start at 0!).
$sql = "SELECT field1, field2, field3, .... FROM sometable";
$result = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
echo $array[1]['field2']; // display field2 value from 2nd row of result set.
The other answers do work - however OP asked for all rows and if ALL fields are wanted as well it would much nicer to leave it generic instead of having to update the php when the database changes
$query="SELECT * FROM table_name";
Also to this point returning the data can be left generic too - I really like the JSON format as it will dynamically update, and can be easily extracted from any source.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo json_encode($row);
}
You can do it without a loop. Just use the fetch_all command
$sql = 'SELECT someFieldName FROM yourTableName';
$result = $db->query($sql);
$allRows = $result->fetch_all();
HERE IS YOUR CODE, USE IT. IT IS TESTED.
$select=" YOUR SQL QUERY GOOES HERE";
$queryResult= mysql_query($select);
//DECLARE YOUR ARRAY WHERE YOU WILL KEEP YOUR RECORD SETS
$data_array=array();
//STORE ALL THE RECORD SETS IN THAT ARRAY
while ($row = mysql_fetch_array($queryResult, MYSQL_ASSOC))
{
array_push($data_array,$row);
}
mysql_free_result($queryResult);
//TEST TO SEE THE RESULT OF THE ARRAY
echo '<pre>';
print_r($data_array);
echo '</pre>';
THANKS

Categories