I'm trying to get somes fields of a DB to import in another DB. So, I've connected to my DB with mysqli.
$mysqli = new mysqli("localhost", "root", "password", "db_name");
if ($mysqli->connect_errno) {
echo "$mysqli->connect_errno";
} else {
echo "You're IN"."<br />";
}
Now, I select the PK of the table:
$emails = $mysqli->query("SELECT email FROM customers WHERE date_first_order IS NOT NULL AND date_first_download IS NOT NULL");
I know that I've an array at this moment in $emails. So, I use a foreach loop.
foreach($emails as $email) {
$email = $email["cl_email"];
$query_name = $mysqli->query("SELECT name FROM customers WHERE email = $email");
$query_lastname = $mysqli->query("SELECT lastname FROM customers WHERE email = $email");
echo $email." ".$query_name." ".$query_lastname."<br />";
}
Here is my problem, with the query_name and query_lastname vars I get an array, an not an String. So, How I can get the field that I'm looking for?
Thanks.
When using MySQLi you should use mysqli_result::fetch_assoc() if you want to get each row as an associative array. http://php.net/manual/en/mysqli-result.fetch-assoc.php
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
I hope this is a string, and you should firstly place it into ''.
$relation= $mysqli->query("SELECT name, lastname FROM customers WHERE email = $email");
-----------------------------------------------------------------------------^------^
And fetch row.
$row = $relation->fetch_row());
Secondly, you can simply return from array the wanted key.
echo $email . " " . $row["name"] . " " . $row["lastname"] . "<br />";
As mentioned by #jonathon mysqli-result::fetch-assoc() should help you with this. Also, i don't see any reason you have to do these queries. I believe you can get the desired output into single query too :)
$query_name = $mysqli->query("SELECT email,name,lastname FROM customers WHERE date_first_order IS NOT NULL AND date_first_download IS NOT NULL");
while ($row = $query_name->fetch_assoc()) {
print $row['email'].$row['name'].$row['lastname'];
}
You could use implode(",",$yourvariable);
It changes your array to a string. you may want to separate the results with a comma or you can just put ("",$yourvariable);
Hope this helps!:)
Related
When I fetch items from a database using php and mysql, I usually just push each row into an array:
$db = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s", mysqli_connect_error());
exit;
}
mysqli_set_charset($db, 'utf8'); //important! or it won't echo the array
$data = array();
$q = "SELECT distinct(procedure_codes), procedure_name FROM `hospital_transparency_data` order by procedure_codes";
$result = $db->query($q);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$data[] = $row; //whole row goes in
}
$db->close();
echo json_encode($data);
But in this case, I want to push each item in the $row into the array individually because I want to add a dollar sign to one of the row items. I still want the name of the field associated with its value, I guess kind of like "full_payer_name"-->$row["full_payer_name"]. How would I do that?
$datastring = $_POST['datastring'];
$q = "SELECT procedure_name, procedure_codes, hospital_name, raw_description, full_payer_name, plan_type, price FROM `hospital_transparency_data` where " . $datastring . " order by procedure_name, hospital_name, full_payer_name";
$result = $db->query($q);
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
//Add this row to the reply
array_push($data, $row["procedure_name"], $row["procedure_codes"], $row["hospital_name"], $row["raw_description"], $row["full_payer_name"], $row["plan_type"], "$" . $row["price"]);
//works, but doesn't have the field name associated with the value
}
Just add the $ to the row element before pushing onto the array.
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$row['price'] = '$' . $row['price'];
$data[] = $row; //whole row goes in
}
You can add it as part of the SQL, this means you don't need to do anything special with the result set. Use CONCAT('$', price) to add it...
$q = "SELECT procedure_name, procedure_codes, hospital_name,
raw_description, full_payer_name, plan_type,
CONCAT('$', price) as price
FROM `hospital_transparency_data`
where " . $datastring . "
order by procedure_name, hospital_name, full_payer_name";
You may also be able to use fetch_all which stops you having to loop over each row to add it in.
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];
}
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);
I have a mysql table in which I keep e-mail addresses. The structure is as follows:
id || email
However, how do I actually output those e-mail addresses, separated by commas, in php?
Thanks in advance for your help!
Use:
<?php
$query = "SELECT GROUP_CONCAT(t.email) AS emails
FROM YOUR_TABLE t"
// Perform Query
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)) {
echo $row['emails'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
References:
mysql_query
GROUP_CONCAT
Third hit on Google for "php mysql": http://www.freewebmasterhelp.com/tutorials/phpmysql
You probably need to read up on the basics, it's not complicated and will only take a few minutes to glance over it and get you started.
Option 1:
$sql = "SELECT GROUP_CONCAT(email ORDER BY email ASC SEPARATOR ', ') AS emails FROM emails";
$res = mysql_query($sql);
list($emails) = mysql_fetch_row($res);
echo $emails;
Option 2, so you can do more with all the emails later on:
$emails = array();
$sql = "SELECT email FROM emails ORDER BY email ASC";
$res = mysql_query($sql);
while ($r = mysql_fetch_object($res)) {
$emails[] = $r->email;
}
// as a list
echo implode(', ',$emails);
// or do something else
foreach ($emails as $email) {
// ...
}
Do something like:
while ($output = mysql_fetch_array($query_results)) {
echo $output['id'] . ", " . output['email'];
}
Ok I have a table with a few fields. One of the fields is username. There are many times where the username is the same, for example:
username: bob
password: bob
report: 1
username: bob
password: bob
report: 2
I did a SQL statement to select * where username='bob'; but when I do the following PHP function, it will only return the last result:
$thisrow = mysql_fetch_row($result);
I need to get every field from every row. How should I go about doing this?
$mainsection="auth"; //The name of the table
$query1="select * from auth where username='$user'";
$result = mysql_db_query($dbname, $query1) or die("Failed Query of " . $query1); //do the query
$thisrow=mysql_fetch_row($result);
echo "Study: " . $thisrow[1] . " - " . $thisrow[5];
Sorry for such a dumb question. I can't seem to get the while loops of more than one field working for the life of me.
mysql_fetch_row fetches each row one at a time. In order to retrieve multiple rows, you would use a while loop like this:
while ($row = mysql_fetch_row($result))
{
// code
}
Use a loop, and use mysql_fetch_array() instead of row:
while($row = mysql_fetch_array($result)) {
echo "Study: " . $row[1] . " - " . $row[5];
// but now with mysql_fetch_array() you can do this instead of the above
// line (substitute userID and username with actual database column names)...
echo "Study: " . $row["userID"] . " - " . $row["username"];
}
I suggest you to read this:
http://www.w3schools.com/php/php_mysql_select.asp
It will give you an overview idea of how to properly connect to mysql, gather data etc
For your question, you should use a loop:
while ($row = mysql_fetch_row($result)){//code}
As said by htw
You can also obtain a count of all rows in a table like this:
$count = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS count FROM table"));
$count = $count["count"];
You can also append a normal WHERE clause to the select above and only count rows which match a certain condition (if needed). Then you can use your count for loops:
$data = mysql_query("SELECT * WHERE username='bob'");
for ($i = 0; $i
Also, mysql_fetch_array() is usually a lot easier to use as it stores data in an associative array, so you can access data with the name of the row, rather than it's numeric index.
Edit:
There's some kind of bug or something going on where my second code block isn't showing everything once it's posted. It shows fine on the preview.
I like to separate the DB logic from the display. I generally put my results into an array that I can call within the HTML code. Purely personal preference; but here's how'd I'd approach the problem: (I'd take the $sql out of the error message in production)
<?php
$sql="
SELECT *
FROM auth
WHERE username='$user';
";
$result = mysql_query($sql)
or die("Failed Query : ".mysql_error() . $sql); //do the query
while ($ROW = mysql_fetch_array($result,MYSQL_ASSOC)) {
$USERS[] = $ROW;
}
?>
HTML CODE
<? foreach ($USERS as $USER) { ?>
Study: <?=$USER['dbFieldName'];?> - <?=$USER['dbFieldName2'];?>
<? } //foreach $USER ?>
$qry=mysql_query(select * where username='bob');
if(mysql_num_rows($qry))
{
while($row=mysql_fetch_array($qry,MSQL_NUM))
{
echo $row[0]." ".$row[1]." ".$row[2]."<br>";
}
}