PHP PDO error undefined index serial - php

I'm about to pull my hair out. I can't get the undefined index to go away. Basically where it says echo htmlspecialchars($r['serial']) I want it to list the item out of the database table.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->setFetchMode(PDO::FETCH_OBJ);
while ($r = $q->fetch());
} catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
$r = $q->fetchAll();
echo htmlspecialchars($r['serial'])
?>

You are referring to the result as an associative array where you expect to have the key 'serial'. This is the behavior of PDO::FETCH_NAMED, not PDO::FETCH_OBJ. Just use the right fetch mode, and you should be fine:
$q->setFetchMode(PDO::FETCH_NAMED);

see the below code, the fetchAll will get the results in an associative array, so you can get the data like $row['serial'] and use it later.
also added the execute() on the pdo statement obj.
<?php
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "SELECT serial, model, deviceCondition, sealCondition, location, deployDate, weight, notes FROM $sql_table ORDER BY serial";
$q = $conn->prepare($sql);
$q->execute(); // make sure to add this
$results = $q->fetchAll();
foreach($results as $row) {
echo htmlspecialchars($row['serial']) . "<br>";
//if you want to use the serial later, just store it into an array
$serials [] = htmlspecialchars($row['serial']);
}
// while ($r = $q->fetch()); this is not needed because of the fetchAll statement above
}
catch (PDOEException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
?>
</div>
<?php
//$r = $q->fetchAll(); not needed here, we did it above already
?>
<?php
//echo htmlspecialchars($r['serial']); use your array from above
print_r($serials);
?>
let me know if it helps

Related

echo selected SQL row data using PHP

If I collect multiple row data from SQL, I will have to use foreach loop or something else to display that data properly.
How to use these PHP strings without using foreach loop ?
Following is my SQL query
$results = $mysqli->query('SELECT * FROM specs where id in ('.$id1.','.$id2.','.$id3.','.$id4.') ');
It will result data from 4 different rows.
The above code is just an example, below is the exact code I am using in my page.
try{
$pdo = new PDO("mysql:host=localhost;dbname=databse", "user", "password");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt select query execution
try{
$sql = "SELECT * FROM specs WHERE id IN($id1,$id2,$id3,$id4)";
$result = $pdo->query($sql);
$results = $result->fetchAll();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
Currently, the data is displayed using the following
<tr>
<td>Brand</td>
<?php foreach ($results as $result){ ?>
<td> <strong><?php echo $result['brand']; ?></strong> </td>
<?php } ?>
</tr>
There will be total 4 results, I wan to use that 4 results separately.
If the results are
Samsung, Sony, Apple, LG - how can I echo the "Apple" only using PHP string ?
Fetch all the rows. If you have the MySQL Native Driver:
$rows = $results->fetch_all(MYSQLI_ASSOC);
Otherwise, fetch with a loop:
while($rows[] = $results->fetch_assoc());
Then you can access them by row:
echo $rows[0]['brand']; // first row
echo $rows[1]['brand']; // second row
But that's not very useful. If you have something unique that you want to use (I use brand as an example though it's probably not), then just index on that:
$rows = array_column($results->fetch_all(MYSQLI_ASSOC), null, 'brand');
// or
while($row = $results->fetch_assoc()) { $rows[$row['brand']] = $row; }
// then
echo $rows['apple']['model'];

How to get single value from database with php

I am trying to get a single value from database and store it in a variable Here is the structure of my Database
mysql_connect("localhost","root","") or die(mysql_error());;
mysql_select_db("test") or die(mysql_error());
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
echo $row['course'] . "<p>";
}
When I use the above code it prints all the courses against my name from data base but I want a specific course name to be selected, like there are 5 courses against my name and i just want all of then separately to be saved in separate variable.
Give this query a try:
SELECT DISTINCT name, GROUP_CONCAT(DISTINCT course ORDER BY course) AS courses;
FROM names
WHERE name = noshair
and change your echo statement to this:
echo $row['courses'] . "<p>";
This should output a list of your course like this -> 'java, c#, php, maths' which you could then put in a variable.
Perhaps you should try the query:
SELECT GROUP_CONCAT(course)
FROM names
WHERE name = noshair;
As side notes, you should stop using mysql_ functions (use mysqli_ or some similar interface). And learn to use parameters in your queries.
Why don't you use php foreach statement like these:
foreach ($row['course'] as $key => $value)
{
echo $value;
}
better still you can use the PHP Implode or Explode method to display them separately.
I think you have to excape the matching value for WHERE:
Try this:
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$result = mysql_query("SELECT * FROM `names` WHERE `name` = 'noshair'");
while($row = mysql_fetch_array($result));
{
$courses[] = $row['course'];
}
var_dump( $courses );
The code saves all the contents to an Array.
Use array to save all courses separately.Then the course name will be save in separate indexes of array like $array[0]="math" and $array[1]="english" .Then use the for loop to save each value in separate variables by setting the condition of loop with total number of values in array.Then the courses will be save separately in different variables like $sub1, $sub2 and so on.Try this code
$con=mysql_connect("localhost","root","")
if(!$con)
{
die('Not connected : ' . mysql_error());
}
$db_selected = mysql_select_db('test', $con);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query('SELECT * FROM names WHERE name = noshair');
while($row = mysql_fetch_array($result));
{
$value=$row['course'] . "<p>";
echo $value;
$array[]=$value;
}
$total=count($array);
for($i=0;$i<$total;$i++)
{
$n=$i+1;
${'sub'.$n} = $array[$i];
}

Using PDO to return a single set of values rather than an array

A very nice person on this site helped me with the following script (and it worked a treat)
<?php
$db = new PDO('mysql:host=HOST;dbname=DATABASE', $user, $pass);
$stmt = $db->prepare('
SELECT
yeast,
rating,
description,
weblink,
image,
sideimage
FROM dowdb_yeast_selector
WHERE
fruit = :fruit
ORDER BY
rating DESC
');
$stmt->bindParam(':fruit',$_POST['fruit'],PDO::PARAM_STR,50);
$stmt->execute();
How do I just echo side image (not as part of a while loop)?
I think (?) I need something like echo '$row[sideimage]' // how simple am I
All of the examples I have looked at so far do not fit my needs :-(
Use PDO::fetchAll, for example;
$stmt->execute();
$arrResults = $stmt->fetchAll();
//$arrResults will be multidimensional
//This will echo the first sideimage
echo $arrResults[0]['sideimage'];
If you want to echo all values of sideimage (ie: all rows), you'd have to iterate through the results;
foreach($arrResults as $arrRow) {
echo $arrRow['sideimage'] . PHP_EOL;
}
Links
pdo::fetchAll
You should use loop pdo::fetch()
while($abc = $stmt->fetch())
{
print_r($abc);
}
If you don't want to use loop try pdo::fetchAll()
$data = $stm->fetchAll();
You could use FETCH_ASSOC
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $res[0]['sideimage'];
or
foreach($res as $key=>$value) {
$image_val = $value['sideimage'];
}

How get all values in a column using PHP?

I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?
For eg:
Table Name: Customers
Column names: ID, Name
# of rows: 5
I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:
SELECT names FROM Customers
and then use the
mysql_fetch_array
PHP function to store those values in an array.
Here is a simple way to do this using either PDO or mysqli
$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);
or, using mysqli
$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['column'];
}
print_r($array);
Array
(
[0] => 7960
[1] => 7972
[2] => 8028
[3] => 8082
[4] => 8233
)
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here :
http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
I would use a mysqli connection to connect to the database. Here is an example:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code:
I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
Since mysql_* are deprecated, so here is the solution using mysqli.
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
$queryStatment = "SELECT * From USERS ";
$testing = displayAllRecords('localhost','root','root#123','email',$queryStatment);
echo $testing;
Here
localhost indicates Name of the host,
root indicates the username for database
root#123 indicates the password for the database
$queryStatment for generating Query
hope it helps
PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');
How to put MySQL functions back into PHP 7
Step 1
First get the mysql extension source which was removed in March:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
Then edit your php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
Restart PHP and mysql_* functions should now be working again.
Step 4
Turn off all deprecated warnings including them from mysql_*:
error_reporting(E_ALL ^ E_DEPRECATED);
Now Below Code Help You :
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$Data[] = $row['names'];
}
You can also get all values in column using mysql_fetch_assoc
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_assoc($result))
{
$Data[] = $row['names'];
}
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Reference
YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY
*
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>

Display mysql data in php function

Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
global $data;
echo $data;
}
but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??
If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did. Does the database value display if you echo it out outside of the function?
Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?
If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");
while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
...
}
Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.
When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("mydbname")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
// then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
echo $row["userid"];
echo $row["fullname"];
echo $row["userstatus"];
}
mysql_free_result($result);
If all this goes well go a little further change a little the while loop.
$myArray = array();
while ($row = mysql_fetch_assoc($result)) {
$myArray[] = $row;
}
mysql_free_result($result);
// now you can start playing with your data
echo $myArray[0];
Small steps...

Categories