Using $_GET to get search term, turn array into requested column [duplicate] - php

This question already has answers here:
fetch single record using PHP PDO and return result
(2 answers)
Closed 6 years ago.
I have not made the change from MySQL_ to PDO until today. Needless to say, the migration is more than a simple headache. So, I need a bit of help. I tried all the search terms I could before registering and asking this question.
My Problem
User types a numeric code into the search box, translates it to
.php?code=term
Script selects all columns from the database where the code is the
code term searched for.
PHP will Echo the results
My Code
if (isset($_GET["code"])) {
//IF USER SEARCHES FOR CODE, RUN THIS. ELSE SKIP.
$crimecode = $_GET["code"];
$crcode = $link->prepare("SELECT * FROM crimecodes WHERE code = :code");
$crcode->bindParam(':code', $crimecode);
$crcode->execute();
$coderesult = $crcode->fetchAll();
echo "<h4>CODE:</h4>";
echo $crimecode;
echo "<br /><h4>DEFINITION:</h4>";
echo $coderesult;
die();
}
Before, it was simple. All I had to do was:
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
But, the ever evolving world has decided to fix something that wasn't broken so now the whole prior code is pointless and you gotta learn something new. Any help is appreciated to get this to work.
Right now, the above PDO code returns definition: ARRAY.
Like literally, the $coderesult prints Array.

The fetchAll() option returns an array containing all of the result set rows (http://php.net/manual/pt_BR/pdostatement.fetchall.php).
$coderesult prints Array because it's actually an array. If you do var_dump($coderesult) you'll see it.
I suppose that you are trying to get one row only. If that's the case, add this line after $coderesult = $crcode->fetchAll();:
$coderesult = $coderesult[0];
Then you can
echo $coderesult['definition'];
If you're trying to get more than one row, you need to use foreach to loop through the array.
I suggest you read the php manual for PDO Class or mysqli, wherever you prefer. There's a lot more options than mysql_.
Also, I think it's worth to mention that your previous code
$qcode = mysql_query("SELECT * FROM crimecodes WHERE code = $crimecode");
$fcode = mysql_fetch_assoc($qcode);
echo $fcode['definition'];
it's vulnerable to SQL Injection.

Related

Display an avergae using PHP and SQL

I'm currently working on a website with a friend and I need to display the average rating for a movie.
So, I have a database with numerous columns (name, mail, etc) including "note".
My friend wrote this code :
<?php
$moyenne = "SELECT avg(note) FROM `annee_1`";
$test = $db->prepare($moyenne);
$test->execute();
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
echo $resultat;
?>
I'm not overly familiar with php or mysql. I know something is wrong (since this doesn't display a number, but just "Array"), but I don't know what.
Any suggestiong, or solution to my problem?
Thanks ! :)
You can access to your result by passing parameter to your array with a while loop. Replace your echo $result by print_r($resultat) and you can check the result you have received.
Your query will return one row with one column. An easy way to get a single value from a query like that is to use
$resultat = $test->fetchColumn();
Instead of
$resultat = $test->fetchAll(PDO::FETCH_ASSOC);
You're seeing "Array" currently because $resultat is an array (because that's what fetchAll reutrns), and when you try to echo it, it gets converted to a string. In PHP, the string representation of any array is "Array". See the documentation here:
Arrays are always converted to the string "Array"; because of this, echo and print can not by themselves show the contents of an array.
But if you use fetchColumn() instead, $resultat won't be an array. Based on your comments, it should be an int.

Basic php - echo mysql, how?

I want it to echo how many posts there are in bestallt where its ID is 1 from the table order and display it as how many posts there are in numbers. I am connected to the database in the PHP file, that's not an issue. I'm just not sure how to put it all down in PHP, quite new to this. I just can't get it to echo what I want, nothing comes out/I get an error.
Any help is appreciated!
Your present code does not fetch the data from the database, it simply echoes the SQL query you have written.
Quite a lot more code goes in to fetching results from a mysql database, and I am not sure reproducing a full explanation here will serve anyone's interests. However, you may wish to view the examples of how to use PDO (a method of using mysql databases from php) here, and then either edit or re-ask your question if you find you have specific difficulties following those examples.
Try this code:
<td>
<?php
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"; // Your SQL query
$response = mysql_query($sql);
if (mysql_num_rows($response) == 0) {
// Your query returned 0 rows!
}
while($row = mysql_fetch_array($response)){
// For each row returned from your query
// $row is an array
// For example, You can use it:
echo $row['data1'];
echo $row['data2'];
echo $row['data3'];
// data1, data2, data3 are the name of the fiels in your database
}
?>
</td>
Have a nice day!
Try this,
$sql = "SELECT count(*) FROM order WHERE bestallt='1'"
$res=mysql_query($sql);
$arr=mysql_fetch_array($res);
echo "<pre>";print_r($arr); //you will get whole array for matching record of your order table if found anything
To learn more, you can check my earlier Answer: how generate report between the two dates using datepicker,ajax,php,mysql.?
In that answer I have described whole working demo.

Trouble retrieving data using PDO syntax, PHP

I'm brand new to the PDO syntax and I'm liking the learning curve! I'm refactoring code - migrating over from archaic mysqli_* methods.
Predictably, I've run into some snags, being a novice. One of the big ones is (forgive if this is a dumb question) retrieving data from the DB and echoing it out on the page. Here is what I have so far:
$getURLid = $_GET['id'];
$idQuery = $connection->prepare("SELECT * FROM pages WHERE page_id = :getURLid");
$idQuery->execute(array(':getURLid' => $getURLid));
$idRetrieved = $idQuery->fetchAll(); // This is the part I'm unclear on.
When I echo $idRetrieved['value'] to the page, nothing shows up. I'm missing something or misunderstanding how it works. Maybe fetchAll isn't what I should be using.
If it is, is a loop necessary to retrieve all rows? I was under the impression that fetchAll would loop through them automatically based on what I've read.
Thanks for the help.
Read the doco for PDOStatement::fetchAll closely. It returns an array of row data.
The type of data representing each row depends on your fetch mode which by default is PDO::FETCH_BOTH. This would mean each row is an array with both numeric and associative keys. If you're only going to access the data associatively, I'd recommend using PDO::FETCH_ASSOC, eg
$idRetrieved = $idQuery->fetchAll(PDO::FETCH_ASSOC);
You would then either need to loop or access each row via its index, eg
foreach ($idRetrieved as $row) {
echo $row['value'];
}
// or
echo $idRetrieved[0]['value']; // assuming there's at least one row.

Newbie trying to decipher merge command associated code

Someone retired in our group and I'm trying to figure out what his merge statement (and associated code) does so I can determine how to convert some (not all) values to integer before sending up. See comments below for questions. I am an absolute newbie with Microsoft SQL and took a class in php a few years ago, but don't have much experience. I've tried googling the merge command but I'm having trouble with a couple parts in it. See my questions below. (// ?)
I've looked at:
http://php.net/manual/en/pdo.query.php
http://stackoverflow.com/questions/4336573/merge-to-target-columns-using-source-rows
http://pic.dhe.ibm.com/infocenter/iseries/v7r1m0/index.jsp?topic=%2Fsqlp%2Frbafymerge.htm
I realize these are basic questions but I'm trying to figure it out and nobody around here knows.
function storeData ($form)
{
global $ms_conn, $QEDnamespace;
//I'm not sure what this is doing?? I thought this was where it was sending data up??
$qry = "MERGE INTO visEData AS Target
USING (VALUES (?,?,?,?,?,?,?,?,?,?))
AS Source (TestGUID,pqID, TestUnitID, TestUnitCountID,
ColorID, MeasurementID, ParameterValue,
Comments, EvaluatorID, EvaluationDate)
ON Target.pqID = Source.pqID
AND Target.MeasurementID=Source.MeasurementID //what is this doing?
AND Target.ColorID=Source.ColorID //what is target and source?
WHEN MATCHED THEN
UPDATE SET ParameterValue = Source.ParameterValue,
EvaluatorID = Source.EvaluatorID, //where is evaluatorID and source? My table or table we're send it to?
EvaluationDate = Source.EvaluationDate,
Comments = Source.Comments
WHEN NOT MATCHED BY TARGET THEN
INSERT (TestGUID,
pqID, TestUnitID, TestUnitCountID,
ColorID, MeasurementID,
ParameterValue, Comments,
EvaluatorID, EvaluationDate, TestIndex, TestNumber)
VALUES (Source.TestGUID, Source.pqID,
Source.TestUnitID,
Source.TestUnitCountID,
Source.ColorID, Source.MeasurementID, Source.ParameterValue,
Source.Comments, Source.EvaluatorID, Source.EvaluationDate,?,?);";
$pqID = coverSheetData($form);
$tid = getBaseTest($form['TextField6']);
$testGUID = getTestGUID($tid);
$testIndex = getTestIndex ($testGUID);
foreach ($form['visE']['parameters'] as $parameter=>$element)
{
foreach ($element as $key=>$data)
{
if ( mb_ereg_match('.+evaluation', $key) === true )
{
$testUnitData = getTestUnitData ($form, $key, $tid, $testGUID);
try
{
//I'm not sure if this is where it's sent up??
//Maybe I could add the integer conversion here??
$ms_conn->query ($qry, array(
$testGUID, $pqID,
$testUnitData[0], $testUnitData[1], $testUnitData[2],$element['parameterID'], $data, $element['comments'] $QEDnamespace->userid, date ('Y-m-d'), $testIndex, $tid));
}
catch (Zend_Db_Statement_Sqlsrv_Exception $e)
{
dataLog($e->getMessage());
returnStatus ("Failed at: " . $key);
}
}
}
}
}
This is a bit long for a comment. If you are using SQL Server, then look at the SQL Server documentation on merge. All the SQL Server documentation is on line, and it is very easy to find via Google (and perhaps even easier using Bing).
The purpose of the MERGE command is to do both inserts and updates in one step. Basically, you have a table that has new data ("source") and a table to be updated ("target"). When a record matches, then update the existing record in the target with matching record in source. When a record doesn't match, then insert it into target.
The main advantage of MERGE over two statements is not necessarily the elegant and intuitively obvious syntax. The main advantage is that all the operations occur in a single transaction, so either they all succeed or all fail as one.
The syntax actually isn't that bad. I would recommend that you set up a test database and try a few examples on your own, so you at least understand the syntax. Then, return to this code. When doing so, print out the resulting merge statement and put it in SQL Server Management Studio, where you will have nice color coded key words for the statement. Then go through it step by step, and you'll probably find that it makes lots of sense.

Problem with a SELECT WHERE query

Got a relatively simple MySQL query that I'm pulling using php with the following code:
$employeeNames = mysql_query(
"SELECT *
FROM employees
WHERE team=\"1st Level Technical Support_a\"
LIMIT 0,5000") or die(mysql_error());
$employeeNumRows = mysql_num_rows($employeeNames);
echo $employeeNumRows;
while ($row = mysql_fetch_array($employeeNames, $employeeNumRows)) {
echo $row['full_name'];
}
Now, if I run the query on the first line in SQL it gives me 18 results. If I echo $employeeNumRows it prints 18. Nothing else after that though.
If I change "1st Level Technical Support_a" to any other team in the table, it will bring up the proper results using PHP
This is the weirdest problem I've come across using MySQL/PHP - can anyone help? Has anyone seen something like this before?
Try removing the second parameter from your call to mysql_fetch_array, so that it reads mysql_feetch_array($employeeNames). See the documentation of the function to see how to use it properly.

Categories