retrieving a mysql query - php

I have written a mysql query and fetched the result as an assoc array using mysql_fetch_assoc().The query returns a list for two fields.I am looping through this field using through the result array and am extracting the value.how do i display the two fields since doing a plain echo is not working for me?The code which i have written is
Thanks in advance.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract( $s );
echo $x . " - " . $y . "<br />";
}

I advise against using extract. it makes code very hard to follow.
I'd just do this:
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) ) {
echo $s['x'], ' - ', $s['y'], '<br/>';
}

mysql_fetch_assoc returns an array of mappings of key to value. As you didn't retrieve one and two from the database, $one and $two ($s['one'] and $s['two'] respectively) don't exist. Therefore do something like this, using the columns you selected as keys.
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
echo $s['x'] . " - " . $s['y'] . "<br />";
}
Or if you want to continue using extract (I don't recommend it, it can lead to some hard to track down bugs)
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink);
while( $s= mysql_fetch_assoc( $result ) )
{
extract($s);
echo $x . " - " . $y . "<br />";
}

extract is a bad practice, furthermore your columns are probably called x and y and not one and two.
i suggest using the following:
echo htmlspecialchars($s['x']), ' - ', htmlspecialchars($s['y']);

According to your SELECT statement mysql_fetch_assoc() returns an array like array('x'=>something, 'y'=>something)and extract() would "translate" that to $x='something' and $y='something', not $one and $two.
Try
error_reporting(E_ALL);
$query = "SELECT x,y FROM table";
$result = mysql_query( $query , $resourcelink) or die(mysql_error());
echo 'there are ', mysql_num_rows($result), " records in the result set\n";
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo $row['x'], ' ', $row['y'], "\n";
}

Related

Get 2 variables in sql and subtract them in PHP

I have multiple rows with data, some with data in mysql table kjoring and some that don't.
I am able to echo both $km1 and $km2 correctly, but I am unable to subtract them to find the result and echo $km0
$sqlq = "SELECT kjoring FROM oko WHERE kjoring!='' ORDER BY logdate DESC LIMIT 2";
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$conn = new mysqli($servername, $username, $password, $dbname);
$result = mysqli_query( $conn , $sqlq );
if ( $result->num_rows > 0 ) {
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
$km0 = $km1 - $km2 ;
}
}
echo $km0 ;
First things first: Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!
Next:
// $sqlq = 'SELECT ... FROM ... ORDER BY ... LIMIT'
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
When you add your WHERE conditions after the LIMIT there WILL be a syntax error returned by your DB. You need to add the WHERE condition after the FROM and in front of the ORDER BY.
$sqlq = 'SELECT ... FROM ... ';
if ( array_key_exists( 'field' , $out ) ) {
$sqlq = $sqlq . " where field = '" . $out['field'] . "'" ;
}
$sqlq .= 'ORDER BY ... LIMIT ...';
Now to the 2 results:
while($row = mysqli_fetch_array($result)) {
$km1 = $row[0];
$km2 = $row[1];
When printing your row using var_dump() you will notice that there is only 1 column. You selected just one.
Using mysqli_fetch_all($result,MYSQLI_ASSOC); you will get an array containing both rows. Using this you can then do your computations.
PHP: mysqli_fetch_all()

Output of DISTINCT and <> from SQL Query issue

I am obtaining some values from an array and making a match against these values in an SQL Query.
The code for this is as follows:
foreach($files as $ex){
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$sql = 'SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` <> "' . $search . '" LIMIT 4';
}
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
The issue that I am having is that the <> seems not to be working.. I have even tried using the != operator, but still having the same issue.
The output of $search from the array are :
101m
102l
102m
103l
The output of SQL from the query is still:
101m
102l
102m
103l
Your code doesn't seem that logical, as you generate numerous SQL statements and then just execute the last one.
However I assume what you want to do is take a list of files, extract a string from each file name and then list all the pdb_code values from the table which are not already in the string.
If so something like this would do it. It takes each file name, extracts the sub string and escapes it, putting the result into an array. Then it builds one query, imploding the array to use in a NOT IN clause:-
<?php
$search_array = array();
foreach($files as $ex)
{
$search = substr($ex,3,4);
echo $search . '<br>';
echo '<br>';
$search_array[] = mysql_real_escape_string($search);
}
if (count($search_array) > 0)
{
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('" . implode("','", $search_array) . "') LIMIT 4";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo 'SQL' . $row['pdb_code'] .'<br>';
$pdb[] = $row['pdb_code'];
}
}
You have to use not in:
SELECT * FROM table_name WHERE column_name NOT IN(value1, value2...)
Try this:
$searchIds = implode(',',$search);
$sql = "SELECT DISTINCT `pdb_code` FROM pdb WHERE `pdb_code` NOT IN ('$searchIds') LIMIT 4";

Separate records with comma

I'm new to php and I want to separate the records with a comma.
Database:
the table in sql
I use this code to get the data:
<?php
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result))
{
echo "Test: " . $row["value"]. "<br>";
}
mysqli_close($con);
?>
It return twice as:
Test: Test
Test: Test1
I want to separate the records with a ',' like this:
Test: Test, Test1
Store your values in an array and than implode with ",". You will get the result:
$id = get_the_ID();
$sql = "SELECT *
FROM tablename
WHERE parent_id=$id";
$result = $conn->query($sql);
$yourArr = array();
while($row = mysqli_fetch_array($result))
{
$yourArr[] = $row["value"];
//echo "Test: " . $row["value"]. "<br>";
}
echo "Test: ". implode(",",$yourArr);
You can do this entirely in MySQL using GROUP_CONCAT:
<?php
$id = get_the_ID();
$sql = "SELECT `parent_id`, GROUP_CONCAT(`value` SEPARATOR ', ') AS comma_separated_values
FROM tablename
WHERE `parent_id` = '$id'
GROUP BY `parent_id`";
$result = $conn->query($sql);
while ($row = mysqli_fetch_array($result))
{
echo 'Test: ' . $row["comma_separated_values"]; // Test: test, test2
}
mysqli_close($con);
?>
You should change the "comma_separated_values" name to something more appropriate for your data.
In your particular case, you would not need the while() loop either as we're limiting the MySQL to a single row.
If you were to remove the WHEREparent_id= '$id' from the SQL query, then you could return the results of multiple parent_id values. For example:
while ($row = mysqli_fetch_array($result))
{
echo 'Parent ' . $row['parent_id'] .': ' . $row["comma_separated_values"] . '<br>';
}
Would return:
Parent 292: Test1, Test2
Parent 293: Test3, Test4
Parent 294: Test5, Test10, Test50
etc...
you can use update query for this
$query="Update tablename set value=CONCAT(value,',test1') where parentid='295'";
$result=mysqli_query($conn,$query);

Explode array and define Variables

I have the following which returns
"soccertennisfootball"
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "{$row['interest']}";
}
Can somebody please explain how I can explode the data and assign it as variables? I've been looking around at tutorials but they all seem to have some sort of delimeter?
Ive tried the following oly its acting very weird and printing out multiple times?
the following...
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
$interest1 = $interests[0];
$interest2 = $interests[1];
$interest3 = $interests[2];
print $interest1 . " - " . $interest2 . " - " . $interest3;
}
Prints out
"Tennis - Tennis - Footy - Tennis -Soccer - Footy"
They aren't a single string, you're just echoing it out. Store it somewhere. This code stores it in a new array. It may be useful but it really depends on what you want to do with it.
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$interests[] = $row['interest'];
}
In each iteration of the while loop, you can only access one of the results (first 'soccer', then 'tennis', then 'football'). In your second code block, you're trying to somehow access all three inside the while loop.
Instead, inside the while loop, push that single result into an array:
$interests = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$interests[] = $row['interest'];
//First 'soccer' will be pushed into $interests, then 'tennis', then 'football'.
}
Now that you have all the values in the array, you can access each individually. This is done OUTSIDE the while loop:
echo $interests[0] . ' - ' . $interests[1] . ' - ' . $interests[2];
This will print "soccer - tennis - football".
Alternately, like some have said, you can loop through the $interests array and echo each value, or do whatever else you'd like with them.
Put them in an array, then do as you will with it after.
$interests = array();
while (...)
{
$interests[] = $row['interest'];
}
Use extract method from php http://php.net/manual/en/function.extract.php
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
extract($row);
echo $interest;
}
Use below snippet to store values in array
$interestsquery = "SELECT * FROM user_interests WHERE user_id = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$result = array();
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$result[] = $row['interest']
}
print_r($result);
Given your clarifications (using MySQL, interest is the only column, and sample output) I would suggest using GROUP_CONCAT(). This puts it all on the MySQL side and allows you to pull the single row from $result.
Try the following sample query:
$query = "SELECT GROUP_CONCAT(interest SEPARATOR ' - ') FROM user_interests
WHERE user_id = " . $usersClass->userID() . "
GROUP BY user_id";

Is there any way to tell user how many rows are in a table?

Let's say I have a table full of names and I want users to know how many names are there.
What would be the output process be?
$result = mysql_query('SELECT Count(*) FROM table') or die('error');
$count = mysql_result($result, 0, 'count(*)');
echo $count;
If you wanted unique names only,
SELECT COUNT(DISTINCT name_column) FROM table_name
If you're filling the table from an array, you can use count($array) in your php code to list the number of elements in the array.
<?php
$r = mysql_query('SELECT COUNT(*) as cnt FROM table;');
$v = mysql_fetch_assoc($r);
echo 'There are ' . $v['cnt'] . ' rows in the table.';
?>
Just in case you're implementing some kind of pagination and want to also show the total amount of records you could use MySQL's FOUND_ROWS().
e.g.
$start = $page*$itemsPerPage;
$query = "
SELECT SQL_CALC_FOUND_ROWS
x,y,z
FROM
foo
LIMIT
$start, $itemsPerPage
";
$result = mysql_query($query, $mysql) or die(mysql_error());
while( false!==($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo
htmlspecialchars($row['x'], ENT_QUOTES, 'utf-8'), ' ',
htmlspecialchars($row['y'], ENT_QUOTES, 'utf-8'), ' ',
htmlspecialchars($row['z'], ENT_QUOTES, 'utf-8'), ' ',
"<br />\n";
}
$query = 'SELECT FOUND_ROWS()';
$result = mysql_query($query, $mysql) or die(mysql_error());
$total = mysql_result($result, 0, 0);
echo $total, ' record(s) found';
You can simply do:
$sql = 'SELECT Count(`id`) as c FROM table';
$ok = mysql_query($sql);
if($ok){
$v = mysql_fetch_assoc($ok);
echo 'There are '.$v['c'].' names in the table.';
}else{
echo 'MySQL error: '.mysql_error();
}

Categories