Display single result from database where ID matches using mysql and php - php

I am having some trouble displaying a single field from the db based on an ID number.
I want to trying to display the "C_Type_of_Referral" if the ID matches. I am sure the code is a mess of crap but I am still at the VERY early stages of learning how to do things in mysql and php.
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = '70'";
$result = mysql_query($query) or die('Error : ' . mysql_error());
list($C_Type_of_Referral) = mysql_fetch_array($result);
Then I am trying to display the result using the code below:
echo ((isset ($_POST['C_Type_of_Referral']) && $_POST['C_Type_of_Referral'] == 'AS') || ($C_Type_of_Referral == 'AS'));
The code above returns the value of 1.
echo ($_POST['C_Type_of_Referral']);
The code above returns nothing.
Where am I going wrong?
Thanks for any help!

Let me start with: Use mysqli instead of mysql, especially when you are starting. Mysql is getting outdate, so start with the right one :)
$query = "SELECT C_Type_of_Referral FROM Ctable WHERE C_ID = 70 LIMIT 1";
$result = mysql_query($query) or die('Error : ' . mysql_error());
$fetch = mysql_fetch_assoc($result);
echo $fetch['C_Type_of_Referral']; // <- this is what you are looking for
if( $fetch['C_Type_of_Referral']=='AS'){ echo 'AdServices'; }
elseif( $fetch['C_Type_of_Referral']=='VS'){ echo 'VisServices'; }
else{ echo 'Nothing of the kind'; }
Things I've done:
- removed quotes arround 70. Integers should not use quotes.
- Added 'limit 1'. This will speed things up in the long run. If you want 1 line, use limit 1
- Changed fetch_array to fetch_assoc ( you'll have to find out why yourself ;) )
Small note: keep table and columnnames lowercase, some systems might give you troubles when you use uppercase characters

Related

MySQL query's suceed in PHPMyAdmin but not in the PHP Script itself

Just while playing around with Querying in PHP i ran into some trouble. The title of this post explains the problem. When i run a query in PHPMyAdmin the results will be different from the results i get in the PHP program itself. Here is the code i am using. Sorry if it looks a little odd i've been cutting and pasting things all over the place in a frantic attempt to get it working.
$connect = array('username'=>'root', 'host'=>'127.0.0.1', 'password'=>'');
$link = mysql_connect($connect['host'], $connect['username'], $connect['password']) or die('Error creating link: ' . mysql_error());
mysql_select_db('testing_pages', $link) or die('Error connecting to database: ' . mysql_error());
$sql = "SELECT `name` FROM `names`";
$query = mysql_query($sql, $link) or die('Query Failed! Check error:<br/><br/>' . mysql_error());
$query_2 = mysql_fetch_array($query);
$query = $query_2;
$loop = count($query);
$count = 0;
while($count <= $loop) {
echo $query[$count] . '<br/>';
$count++;
}
see, what im trying to get it to do is read all the names, pop it into an array, then print them out with a while loop. But it only seems to return 1 result and thats the first name in the databse. but when i run the EXACT query through phpmyadmin it will return every name in the database... Another odd thing, when using the 'count' function to get the number of values in the array is claims that there are 3 values, but during the loop it just prints out the first name, then for the second two it returns an 'Undefined index'.
Hope i dont seem like a noob right now... And i hope i explained everything well. Thanks to anyone who can help.
mysql_fetch_array fetches one row in the form of an array. Here are the docs.
And pay attention to that big warning message at the top of the page when you read the docs...

MySQL: multiple search/select queries at the same time?

I have a question on how to go about the next phase of a project I am working on.
Phase I:
create a php script that scraped directory for all .txt file..
Open/parse each line, explode into array...
Loop through array picking out pieces of data that were needed and INSERTING everything into the database (120+ .txt files & 100k records inserted)..
this leads me to my next step,
Phase II:
I need to take a 'list' of several 10's of thousand of numbers..
loop through each one, using that piece of data (number) as the search term to QUERY the database.. if a match is found I need to grab a piece of data in a different column of the same record/row..
General thoughts/steps I plan to take
scrape directory to find 'source' text file.
open/parse 'source file'.... line by line...
explode each line by its delimiting character.. and grab the 'target search number'
dump each number into a 'master list' array...
loop through my 'master list' array.. using each number in my search (SELECT) statement..
if a match is found, grab a piece of data in another column in the matching/returned row (record)...
output this data.. either to screen or .txt file (havent decided on that step yet,..most likely text file through each returned number on a new line)
Specifics:
I am not sure how to go about doing a 'multiple' search/select statement like this?
How can I do multiple SELECT statements each with a unique search term? and also collect the returned column data?
is the DB fast enough to return the matching value/data in a loop like this? Do I need to wait/pause/delay somehow for the return data before iterating through the loop again?
thanks!
current function I am using/trying:
this is where I am currently:
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
$query = "SELECT guar_nu FROM placements WHERE har_id IN ($harNumArray2)";
echo $query;
$match = mysql_query($query);
//$match = mysql_query('"' . $query . '"');
$results = $match;
echo("<BR><BR>");
print_r($results);
I get these outputs respectively:
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN ("108383442","106620416","109570835","109700427","100022236")
&
Array ( [0] => sample_source.txt )
Total FILES TO GRAB HAR ID's FROM: 1
TOAL HARS FOUND IN ALL FILES: 5
SELECT guar_nu FROM placements WHERE har_id IN (108383442,106620416,109570835,109700427,100022236)
Where do I stick this to actually execute it now?
thanks!
update:
this code seems to be working 'ok'.. but I dont understand on how to handle the retirned data correctly.. I seem to only be outputting (printing) the last variable/rows data..instead of the entire list..
$harNumArray2 = implode(',', $harNumArray);
//$harNumArray2 = '"' . implode('","', $harNumArray) . '"';
//$query = "'SELECT guar_num FROM placements WHERE har_id IN ($harNumArray2)'";
$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (" . $harNumArray2 . ")")
//$result = mysql_query("SELECT har_id, guar_num FROM placements WHERE har_id IN (0108383442,0106620416)")
or die(mysql_error());
// store the record of the "example" table into $row
$row = mysql_fetch_array($result);
$numRows = mysql_num_rows($result);
/*
while($row = #mysql_fetch_assoc($result) ){
// do something
echo("something <BR>");
}
*/
// Print out the contents of the entry
echo("TOTAL ROWS RETURNED : " . $numRows . "<BR>");
echo "HAR ID: ".$row['har_id'];
echo " GUAR ID: ".$row['guar_num'];
How do I handle this returned data properly?
thanks!
I don't know if this answers your question but I think you're asking about sub-queries. They're pretty straightforward and just look something like this
SELECT * FROM tbl1 WHERE id = (SELECT num FROM tbl2 WHERE id = 1);
That will only work if there is one unique value to that second subquery. If it returns multiple rows it will return a parse error. If you have to select multiple rows research JOIN statements. This can get you started
http://www.w3schools.com/sql/sql_join.asp
I am not sure how to go about doing a 'multiple' search/select statement like this?
With regards to a multiple select, (and I'll assume that you're using MySQL) you can perform that simply with the "IN" keyword:
for example:
SELECT *
FROM YOUR_TABLE
WHERE COLUMN_NAME IN (LIST, OF, SEARCH, VALUES, SEPARATED, BY COMMAS)
EDIT: following your updated code in the question.
just a point before we go on... you should try to avoid the mysql_ functions in PHP for new code, as they are about to be deprecated. Think about using the generic PHP DB handler PDO or the newer mysqli_ functions. More help on choosing the "right" API for you is here.
How do I handle this returned data properly?
For handling more than one row of data (which you are), you should use a loop. Something like the following should do it (and my example will use the mysqli_ functions - which are probably a little more similar to the API you've been using):
$mysqli = mysqli_connect("localhost", "user", "pass");
mysqli_select_db($mysqli, "YOUR_DB");
// make a comma separated list of the $ids.
$ids = join(", ", $id_list);
// note: you need to pass the db connection to many of these methods with the mysqli_ API
$results = mysqli_query($mysqli, "SELECT har_id, guar_num FROM placements WHERE har_id IN ($ids)");
$num_rows = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
echo "HAR_ID: ". $row["har_id"]. "\tGUAR_NUM: " . $row["guar_num"] . "\n";
}
Please be aware that this is very basic (and untested!) code, just to show the bare minimum of the steps. :)

why does this search of a mysql database produce no results? Using LIKE for the first time

Editing someone else's code here, so I can't change the field in the database called title or change to MySQLi etc :/
The code connects to the DB without problems, but always pulls in zero results.
$strSQL = "SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')";
$sql = mysql_query($strSQL) or die(mysql_error());
$num_rows = mysql_num_rows($sql);
if ( $q == '' ) {
echo '<p class="black-text">Please provide a search term.</p>';
}
else if ( $num_rows <= 0 ) {
echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>0</b> results.</p>';
}
else {
echo '<p class="black-text">Your search for <b>'.$q.'</b> returned <b>'.$num_rows.'</b> result(s).<br/><br/>';
while($row = mysql_fetch_assoc($sql)) {
echo '- '.$row['title'].' [Read more]<br/>';
}
echo '</p>';
}
Could it be a case issue? I've tried searching for lower and upper strings, but still zero results.
In MySQL single quotes denote strings:
SELECT * FROM newproducts WHERE 'title' LIKE ('%$q%')
Should be
SELECT * FROM newproducts WHERE title LIKE ('%$q%')
Additionally, you are testing for if ($q == '') after you have performed the query - you may want to do that before - but that isn't causing your issue.
And lastly, you are at risk of SQL injection by using potentially unsafe user input - but I'm not going to delve into that as it isn't directly related to your question. Most PHP developers are using prepared statements these days to make their queries safer (and because the old style of running queries is going to be deprecated).

PHP array_sum not working

I am trying to query an SQL table, and then have all the values from one column (it's a "tinyint(1)") added up and then printed, using array_sum. (Currently there are only two rows).
When both rows have a "1" in that column, it gives 2, the correct answer. And when they are both "0" it gives 0, correct again. But when one is "1" and one "0" it gives 2, not 1.
This is my code
$con = mysql_connect("XXX","XXX","XXX");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("XXX_test", $con);
$day = $_GET["day"];
$query = mysql_query("SELECT $day FROM sites");
if (!$query)
{
die('Could not query: ' . mysql_error());
}
$rows = mysql_fetch_array($query);
echo array_sum($rows);
mysql_close($con);
?>
Thanks for any help.
--UPDATE--
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}
This in fact never works correctly.
$rows = mysql_fetch_array($query);
That line only ever fetches the first row. The second row is never retrieved.
The reason it gives 2 using array_sum is that mysql_fetch_array gets the result in two different formats, with keys both by name and number. So you'll get something like this:
array(
0 => '1',
'Tuesday' => '1'
)
Obviously this will always be 2 or 0.
You should almost certainly do a count on the DB server:
SELECT COUNT(*) FROM sites WHERE $day=1
Note, however, that your biggest current problem is the enormous gaping SQL injection hole. Sanitise your input.
mysql_fetch_array() only fetches one row at a time. You need to fetch the rows in a while loop. Then you can either append the results to an array and sum those, or sum them in the loop. You can also SUM in mysql anyway, so you might look into using that.
I'm also obligated to suggest that you use PDO or some other DB wrapper instead of mysql_. You also need to escape variables you use in queries under most circumstances, especially if they come from _GET.
I would suggest doing it in the mysql query:
SELECT SUM($day) FROM sites
also, please escape the $day variable.
More of a comment:
array_sum can not work with the array you're passing to it. You need to pass an array for what the function actually works, like array(1, 2, 3) which will give you 6 then.
Next to that, let MySQL itself calculate the SUM (or COUNT?), so it's easier to handle in your script as others have posted.
I just solved this myself.
With this, if you want to know:
$query = mysql_query("SELECT name, SUM($day) AS Alerts FROM sites");
while($row = mysql_fetch_array($query))
{
echo $row['Alerts'];
echo "<br />";
}

Getting data from MySQL through PHP - am I doing it right?

Simple question I guess, but a fundamental one and I'm not sure of the best practice.
So let's say that I have a database with some IP addresses that I want to display to the user.
Is this a good/secure way/practice?
//--> CONNECT TO DB, etc
$db_query = 'SELECT ip,'
."FROM table "
."GROUP BY ip ";
$result = $db_conn->query($db_query);
echo 'Found '.$result->num_rows.' records';
if($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQLI_BOTH))
{
//POPULATE A HTML TABLE/WHATEVER WITH THE INFO
}
}
I'm mostly concerned about this: $result->num_rows > 0 and this: fetch_array(MYSQLI_BOTH)
I'm asking because I read somewhere that num_rows > 0 can usually mean trouble depending on the situation, for example a user login. In that case I suppose it would num_rows == 1 right?
And also, I haven't fully understood the difference between MYSQLI_BOTH and other forms of fetching.. If you could simple explain them to me and when to use them I would be grateful.
What do you think?
I would add a check to ensure your query was executed OK - and if not output the error :
$result = $db_conn->query($db_query);
// check for error - output the error
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $db_query;
die($message);
}
echo 'Found '.$result->num_rows.' records';
Other than that ... looks OK
EDIT:
To explain MYSQLI_BOTH, the options are MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH ->
MYSQLI_ASSOC = Associative array so the value of the rows can be accessed using $row['column']
MYSQLI_NUM = Numeric array so the values of the rows are accessed using a number $row[n] where n is the number of the column (0 based)
MYSQLI_BOTH = can use both to access values of row either $row[n] or $row['column']
EDIT2:
There is also a function for checking the number of returned rows :
if(mysqli_num_rows($result) == 0){
echo "Sorry. No records found in the database";
}
else {
// loop you results or whatever you want to do
}
EDIT3:
php.net has some excellent docs for the MY_SQLI extension
Two things:
If you only need an associative array, then don't use fetch_array(). Use fetch_assoc().
There's no need to concatenate the query like that, you could use something like:
$sql = "
SELECT
ip
FROM
table
";
This helps with large queries with multiple options in the WHERE clause or JOINs. It's quicker to type out, and you can quickly copy and paste it for checking in phpMyAdmin and the like.

Categories