PHP MySQLi while loop logic - php

I have switched over to the mysqli_ extension for PHP, and I have ran into a bit of an issue.
I have 2 databases. 1 database I am only allowed read privileges, the other I have all privileges. My end goal is to read what I need from database 1, and put it in a table in database 2.
I use a join on database 1 to get all the information I need. I then loop through the results with a while loop. I have a unique id (domainid) in both databases. Where I am encountering the issue is inside the while loop once I have the domainid from the read-only database, I need to check if it exists inside my all-privileges database. I am just unsure of how to accomplish this?
Here is the code:
require 'db/connect.php';
require 'db/connect2.php';
if($result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
")){
if ($count = $result->num_rows) {
while($row = $result->fetch_object()){
$domainid = $row->domainid;
$domain = $row->domain;
$email = $row->email;
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $row->domainid);
$result2->execute();
$result2->bind_result($domainid2);
//$result2->fetch();
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($domainid == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}
}
}
This is what I have tried, but was unsuccessful.
EDIT
Second attempt putting the results into an array then looping through them. The array is correct when I print them out. The issue is with the 2nd execute(); command.
$result = $db->query("
SELECT tblhosting.domain as domain, tblhosting.id as domainid, tblclients.email as email
FROM tblhosting
LEFT JOIN tblclients ON
tblclients.id = tblhosting.userid
");
$domainid_arr = array();
while($row = $result->fetch_object()){
$domainid_arr[] = array(
'domainid' => $row->domainid,
'domain' => $row->domain
);
}
foreach ($domainid_arr as $d) {
echo $d['domainid'], $d['domain'], '<br>';
$result2 = $db2->prepare("SELECT domainid FROM information WHERE domainid = ?");
$result2->bind_param('i', $d['domainid']);
$result2->execute();
$result2->bind_result($domainid2);
while($row2 = $result2->fetch_object()){
$domainid2 = $row2->domainid;
if ($d['domainid'] == $domainid2) {
echo "Information exists in both Databases", '<br>';
}
else{
echo "New Information Added to Database 2", '<br>';
}
}
}

Related

Foreach inside while

I have extracted all the domains I have from my database, I would like to draw all comments to the domains that are added in the database.
$results = $mysqli->query("SELECT domain_name, id_view FROM domain GROUP BY domain_name ORDER BY domain_name");
$comment = $mysqli->query("SELECT domain_name, id_view, comment FROM domain_comment");
$id_array = array();
while($row = mysqli_fetch_array($comment)) {
$id_array[] = $row['comment'];
$id_array[] = $row['id_view'];
}
while($row = mysqli_fetch_array($results))
{
$section = $row['id_view'];
foreach ($id_array as $sectionname) {
if ($sectionname == $section) {
echo $sectionname;
}
}
}
The data it receives is VIEW ID and not Comment, what am I doing wrong?
EDIT:
When he gives the Select query:
$comment = $mysqli->query("SELECT comment FROM domain_comment INNER JOIN domain ON domain_comment.id_view = domain.id_view");
while($row = mysqli_fetch_array($results))
{
while($row2 = mysqli_fetch_array($comment))
{
echo $row2['comment'];
}
}
It prints all the comments at the first domain.
The result I have:
The result he wants:
this part
$id_array[] = $row['comment'];
$id_array[] = $row['id_view'];
What are you trying to do?
inserting comment in the id array? in this case the id_array will have one comment and one id, i dont think this is what you want. and second loop definitely us $row2 it is safer and wont mix up. inner join the quickest way.you are already there i think.
try removing the line
$id_array[] = $row['comment'];
and check.
for innerjoin you can try to innerjoin on two keys i.e also domain.
$comment = $mysqli->query("SELECT comment FROM domain_comment INNER JOIN domain ON domain_comment.id_view = domain.id_view and domain_comment.domain_name = domain.domain_name");
while($row = mysqli_fetch_array($comment)) {
$id_array[$row['id_view']]['comments'][] = $row['comment'];
}
while($row = mysqli_fetch_array($results))
{
$id_array[$row['id_view']]['data'] = $row;
}
You can try this solution after just dump $id_array in this case it would be much more easier to handle data.

Can't get value using json_encode

<!-- QUERY -->
$insertstatement = 'SELECT count(*) co FROM `tbl_user` WHERE username="'.$username.'" AND password="'.$password.'"';
$query123 = mysql_query($insertstatement) or trigger_error(mysql_error()." ".$insertstatement);
while($r = mysql_fetch_array($query123)){
extract($r);
}
<!--GET-->
$co = (int)$co;
$name = $r['name'];
if($co == 1){
$result = array();
$result[] = array("name" => $name,"status" => 1);
}
header('Content-type: application/json');
echo json_encode($result);
if username available / user registered .. the result name is empty.
name :
status : 1
You write the query to get the count of the table having the uername and password given. Then how can you get the name using that query? Please study the things that you did before posting in the forums
1) Your not selecting name column . your only counting the row using count(*)
2) Mysql_* is derprecated try to use mysqli_* or PDO
3) Use prepared statement oR pdo when you dealing with user entered data to avoid sql injection
query :
SELECT count(*) as co, name FROM `tbl_user` WHERE username='username' AND password='password'
Update 1:
You already used extract to change it to variable . so directly access like this $co = (int)$co;
// $name = $r['name']; //no need this line
if($co == 1){
$result = array();
$result[] = array("name" => $name,"status" => 1);
}

Group the output of PDO query

I have a PDO query in which I am doing inner join on two tables and extracting the columns required by me.
Now these two columns are - status, script.
Status can be - passed, failed, incomplete and
script - scripts/testSuite/layer3Features/ManualStaticRouting/manualStaticRoutes.tcl , scripts/testSuite/hostAgentFeatures/dhcp/DHCP IPv6/RelayBBasicFunc/ipv6DhcpRelayEnableDhcpv6RelayGlobally.tcl
the output of --
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
print_r($row);
}
is -
http://pastebin.com/WqcibEyp
the full query is -
$testType = 'TCL';
$getFamily = $conn->prepare('SELECT testcases2.script, results3.status FROM testcases2 INNER JOIN results3 ON testcases2.testcaseID = results3.testcaseID
WHERE testType = :testType');
$getFamily->execute(array(':testType' => $testType));
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key)
{
print_r($row);
$family[] = $key;
}
}
Now here what I want to do is, read the second location of each script (considering scripts at 0) and group all the values which have same stuff in the third location, with status together.
How this can be done.
Please guide.
You need to group your script and status like this,
while($row = $getFamily->fetch(PDO::FETCH_ASSOC))
{
$status[] = $row['status'];
$scripts[] = $row['script'];
}
print_r($scripts);
print_r($status);

Returning each unique user from a MySQL table and also the count of the number of rows for each user

I am using the following MySQL query to generate a table for users in a database. The query is designed to just return one row for each user, even though there are multiple rows for each user. This works fine, however I also need to calculate the number of unique entries for each user, to enter into the table where it states HERE. Do I need to use another query to return the count for all entries, and if so how do I integrate this with the code I already have?
$query="SELECT from_user, COUNT(*) AS num FROM tracks GROUP BY from_user ORDER BY COUNT(*) DESC";
$result=mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$user = $row['from_user'];
echo "<tr>";
echo "<td>".$user."</td>";
echo "<td>uploads (**HERE**)</td>";
echo "<td>favourites (count)</td>";
echo "</tr>";
}
?>
</table>
Because you've already created the custom field 'num', you can use that to get the count!
Add the following line after user = ...
$count = $row['num'];
Then you can
echo "<td>uploads ($count)</td>";
It miss your table stucture to know your field name, but, if i well understand your question you can use count + distinct in mysql.
You can check this answer too.
SELECT DISTINCT(from_user) AS user,
COUNT(from_user) AS num
FROM tracks
GROUP BY from_user
ORDER BY num DESC";
For the second problem you can doing a second query, or do a join tracks .
I think, in your case it's easier to you to do se second query inside the loop to get all detail from 'user' result.
$query1="SELECT DISTINCT(from_user), COUNT(*) AS num
FROM tracks
GROUP BY from_user
ORDER BY COUNT(*) DESC";
$query2="SELECT * FROM tracks";
$result1=mysql_query($query1) or die(mysql_error());
$result2=mysql_query($query2) or die(mysql_error());
$user_array = array();
while ($row = mysql_fetch_array($result1)) {
$user = $row['from_user'];
$num = $row['num'];
$uploads_array = array();
while ($sub_row = mysql_fetch_array($result2)) {
if( $sub_row['from_user'] == $user ) {
//for example only due to the unknown structure of your table
$uploads_array[] = array(
"file_name" => $sub_row['file_name'],
"file_url" => $sub_row['file_url']
);
}
}
$user_array[] = array(
"name" => $user,
"num_entry" => $num,
"actions" => $uploads_array
);
}
// now the table with all data is stuctured and you can parse it
foreach($user_array as $result) {
$upload_html_link_arr = array();
$user = $result['name'];
$num_entry = $result['num_entry'];
$all_actions_from_user_array = $result['actions'];
foreach($all_actions_from_user_array as $upload) {
$upload_html_link_arr[] = sprintf('%s', $upload["file_url"],$upload["file_name"]);
}
$upload_html_link = implode(', ',$upload_html_link_arr);
$full_row = sprintf("<tr><td>%s</td><td>uploads : %s</td><td>favourites (%d)</td></tr>", $user, $upload_html_link, $num_entry);
// now just echo the full row or store it to a table for the final echo.
echo $full_row;
}
I hope this help, mike

Drupal: PHP field for allowed values

I'm working in Drupal 6 with CCK. Under each text field there is a PHP section where you can run some PHP code to get allowed values. I'm running into trouble using an "if" statement to change the allowed values based on user type
So to start, I do a query to determine current users user type. -1 is default user, which is employees and user type id "1", is for site users. What I want is to restrict the site user to only the allowed values they need to see, while allowing employees to edit that value when on the node edit screen with all choices.
The first part of the if statement works. However, the "else" part doesn't work. Is this field set up to deal with control structures?
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
if($res1 == '1'){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res2 = db_query($sql2);
while($row2 = db_fetch_array($res2)){
$rows2[] = $row2['title'];
}
$rows2 = drupal_map_assoc($rows2);
return $rows2;
}
The choices are type=accounts in nodes, however, when a user is created one of the choices is selected and stored in the user table, under a column I created named "account"
If by 'the "else part does not work' you mean that it is never executed, even if user_type_id does not equal 1, it might be the missing db_fetch_array() on $res1. You're comparing your result object directly to the string '1', not the field value.
Here is the working code for this. There may have been a quicker/shorter way to do this.
global $user;
$sql1 = "SELECT user_type_id FROM user_types_user WHERE uid = ".$user->uid." ";
$res1 = db_query($sql1);
while($type = db_fetch_array($res1)){
$types[] = $type['user_type_id'];
}
$resType = $types[0];
if($resType == "1"){
$sql = "SELECT account FROM users WHERE uid = ".$user->uid." ";
$res = db_query($sql);
while($row = db_fetch_array($res)){
$rows[] = $row['account'];
}
$rows = drupal_map_assoc($rows);
return $rows;
}
else {
$sql2 = "SELECT title FROM node WHERE type = 'accounts' ";
$res = db_query($sql2);
while($row2 = db_fetch_array($res)){
$rows2[] = $row2['title'];
}
return $rows2;
}

Categories