MySQL SELECT query seems to skip spaces - php

I'm a beginner with PHP and mySQL and I'm using it for my project. I sort of have a problem with my query.
This is my code:
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
do
{
foreach ($doctnamerow as $cell)
{
$doctnamerowvalue = $cell;
}
} while ($doctnamerow = mysql_fetch_row($doctname));
So the problem I have is that if the doctor's name has a space between it (e.g "AJ Ramos") then it seems to skip the space and just returns "AJ" and not the surname. How do I do this? Thanks =)
edit:
Silly me, It was just an error with my code, I was using $doctnamerowvalue as a value=$doctnamerow for one of my text boxes and forgot to put double quotes, which resulted in value=doctor name and not value="doctor name". Sorry

Flash Code Review:
mysql_* is deprecated. Use MySQLi or PDO.
Your code is wide open to SQL injection
$doctornamerowvalue is overwritten on every iteration
the foreach you are doing is pointless.
variable names are poorly chosen.
Here it is refactored:
// do these in a config file !!!
$db = new PDO('mysql:dbname=' . DB_NAME . ';host=localhost', DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // if you want to use associative arrays
// here is the refactored code
$query = "SELECT name_of_doctor FROM `{$table}` WHERE department_no = :deptno";
$stmt = $db->prepare($query);
$stmt->execute(array(':deptno' => $_REQUEST['deptno']));
$doctors = $stmt->fetchAll();
foreach ($doctors as $doctor) {
echo $doctor['name_of_doctor'] . '<br>';
}
Related to your 'bug'
Check the table structure and data. It's possible that the field contains only the surname, and there is another field that contains the name.
Check the table length - maybe it's too small, so the string is truncated.

try this:
$sql = "your sql syntax";
$result = mysql_query($sql);
$array_of_things = array();
while ($row = mysql_fetch_array($result)) {
$array_of_things[] = $row['table_column_name'];
}
foreach($array_of_things as $val) {
echo $val;
}

used this :
$doctname = mysql_query("SELECT name_of_doctor FROM {$table} WHERE department_no = '{$_REQUEST['deptno']}'");
$doctnamerow = mysql_fetch_row($doctname);
while ($raw = mysql_fetch_row($doctname)) {
echo $raw['name_of_doctor'];
}

Related

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

Get ID for each array element inside second array

I need to get unique ID for each array element inside second array. That ID already exist in table but I cant get them separately. URL that am getting now looks like this: http://page.com/index.php?p=view&m=area&id=173id=552id=768id=36id=217id=
I need just one ID and if first is used set second and so on.
I know that I should use mysqli or PDO and normalized tables but that later, now I need help with this.
This is the code:
$res= mysql_query("SELECT * FROM area WHERE user='$user' ORDER BY date") or die("Error: " . mysql_error());
while($row = mysql_fetch_assoc($res))
{
$id = $row['id'];
$x = array();
$parent = array();
foreach($row as $value)
{
if ($value == $id) continue;
else if ($value == $user) continue;
$result = explode(",", $value);
foreach($result as $newvalue)
{
$query = "SELECT x,firm FROM list where list.x='$newvalue'";
$result = mysql_query($query);
$r = mysql_fetch_assoc($result);
$x[] = $r['x'];
$xx = implode("id=",$x);
$parent[] = $r['firm'];
$list = implode("<a href='index.php?p=view&m=area&$xx'>", $parent)."</a>";
}
}
echo "<td><span>" . $list . "</span>/td>";
}
Thank you
first of all
$list = implode("<a h
should be
$list .= implode("<a h
That URL syntax is not the correct way to pass an array of values to a PHP script. It should use PHP array syntax for the parameter names. Also, you need separate your parameters with an ampersand (&):
http://page.com/index.php?p=view&m=area&id[]=173&id[]=552&id[]=76&8id[]=36&id[]=217
Then you can get the second one by using
$second_id = $_GET['id'][1]; // 552
etc.
FYI, you shouldn't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

how do I fetch and combine data from MySQL then insert into array in PHP

This question is quite specific for my needs, hence I can't find the best way to do this.
What I would like to do is fetch name and surname from the table people and combine both into an array to end up with such results:
"Bob Jones","Tony Wright",.. etc.
I'm using PDO for this. Here is what I have:
$attrs = array(PDO::ATTR_PERSISTENT => true);
// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=new", "root", "root", $attrs);
// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = $pdo->prepare("SELECT name, surname FROM people");
$conn->execute();
$results = $conn->fetchAll();
foreach($results as $row){
$fullName = $row['name'] . "," . $row['surname'];
print_r($fullName);
}
I have tried a few things, I'm just stuck with this code at minute. Any help, or suggestions is much appreciated.
$arr = array();
foreach($results as $row) {
$arr[] = "{$row['name']},{$row['surname']}";
}
echo implode($arr);
You can also resolve this problem in SQL, so foreach would not be needed any more.
Just replace
SELECT name, surname FROM people
with
SELECT CONCAT_WS(' ', name, surname) FROM people
Once you’ve fetched the rows from the database, you need to loop over the result set and assign the combined name to a new array:
<?php
// result set from database
$results = $conn->fetchAll();
// create an empty array to store our names
$names = array();
// loop over result set and add entry to $names array
foreach ($results as $result) {
$names[] = $row['name'] . ' ' . $row['surname'];
}
print_r($names);
$fullname =array();
foreach($results as $row){
$fullName = $row['name'] . " " . $row['surname'];
}
print_r($fullname);

PHP mySQL get table headers function

I'm trying to build a PHP function that allows me to have an array of the headers of MySQL database for finding a particular field.
function table($tablename,$id) {
$post = mysql_query("SELECT * FROM $tablename WHERE ID = '$id'");
}
How would I then output the table headers as effective miniature queries for the row in question.
eg. $post->title, $post->timestamp, $post->field4
You need MySQLi or PDO_MySQL, but in your case:
while ($row = mysql_fetch_assoc($post)) {
echo $row['title'];
}
Documentation
Remember that the use of mysql_* function is discouraged.
A simple PHP Script to fetch the field names in MySQL:
<?php
$sql = "SELECT * FROM table_name;";
$result = mysql_query($sql);
$i = 0;
while($i<mysql_num_fields($result))
{
$meta=mysql_fetch_field($result,$i);
echo $i.".".$meta->name."<br />";
$i++;
}
?>
OUTPUT:
0.id
1.todo
2.due date
3.priority
4.type
5.status
6.notes
Hope this helps! Taken from php.net documentation.
How about mysql_fetch_assoc($post)?
To get all field names int a seperate array:
$post = mysql_fetch_assoc($post);
$fields = array();
foreach($post as $title => $value){
$fields[] = $title;
}
You can use this in a while loop to go through all rows and get theri field values(as well as their names):
while($p = mysql_fetch_assoc($post)){
$title = $p['title'];
$timestamp = $p['timestamp'];
//And so on...
}
Edit: And Pierpaolo is right, you should use another mysql implementation as the old one is gonna be removed in PHP 5.5/5.6 or a bit later...
You can get just the column names by executing this:
DESCRIBE `MyTable`;
It will return a result set that contains Field, Type, Key, etc.
$query = mysql_query("DESCRIBE `MyTable`");
while($result = mysql_fetch_assoc($query)) {
echo $result['Field'] . "\n";
}

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);
?>

Categories