I need to fetch all the info from a query , so I can use it for other purposes, the issue is that I'm just getting 1 result of each kind and I need them all, here is my script:
<?php
require_once 'init.php';
$base_datos = DB::getInstance();
$base_datos->query ("SELECT lname, fname, category,user_id, SUM(points) as Point, SUM(amount)as Amount FROM request GROUP BY user_id");
$get_info = $base_datos->results();
$real_info = $get_info[0];
$name = $real_info->lname;
$last_name = $real_info->fname;
$categories = $real_info->category;
echo "$name";
///var_dump ($get_info);
?>
when echo $name all i get is one name i need to get them all and so on with the other value, when i do var_dump i got all i need, but i need to loop through,I'd searched all around and was not lucky.
this is what I'm trying to output on php page
I'm assuming $get_info is an array of objects based on how your code is currently written. Right now you're setting the first record of $get_info to $real_info.
So to access all of the records loop through $get_info like this.
foreach($get_info as $real_info) {
echo $real_info->fname.' '.$real_info->lname;
}
Related
I am new to php and had chosen to stick to PDO format. I have been able to set up a workable registration and login system, but my challenge is fetching data from my database which would be used in other page of the user profile page I created. I had tried all the many examples and methods I was able to get on the internet but there are not working, or rather I don't know how to use it, where I want to insert the variable will still be empty.
The only fetch function I was able to get will select all the row, for instance, if it is email, it will fetch all the registered emails in the database which is not suppose to be. The email should only be for the user whose profile is opened.
Here are the codes. I am sure someone will help me figure this out. Thanks
$data = $pdo->query("SELECT * FROM databaseName")->fetchAll();
//this one is in the body where i want to insert the email
foreach ($data as $row) {
echo $row['email']."<br />\n";
}
I tried everything my little knowledge of php but all to no avail. If i decide to use any other one, nothing will show.
You can try other alternative to achieve the same,
$stmt = $pdo->query('SELECT * FROM databasetable');
while ($row = $stmt->fetch())
{
echo $row['email'] . "\n";
}
If you are only interested in the email from the returned results, I would look to do the following:
$stmt = $pdo->query('SELECT `email` FROM databasetable');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $row['email'] . "\n";
}
Or
$stmt = $pdo->query('SELECT `email` FROM databasetable');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC))
foreach($data as $row)
{
echo $row['email'] . "\n";
}
If you want to check that the data coming back is good, I would add a "print_r($data);".
You can just take the first element of the results.
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetchAll(PDO::FETCH_ASSOC)[0];
or use fetch()
$stmt = $pdo->query('SELECT `email` FROM databasetable LIMIT 1');
$data = $stmt->fetch(PDO::FETCH_ASSOC);
I´ve also put a LIMIT at the end of your query, so you dont fetch unneeded data.
Unless I am missing something then surely you should be specifying a where in your SQL query, why would you get the entire database and loop through it until you find the email you want?
When you redirect the logged in user you must(or if you aren't then you should) be passing something about the user, e.g setting the userid in the session. Then you can use this to create more useful profile data with a query that says select email from table where userid = :userid - then when you fetch the result you will have the data you need.
Naturally I can't write the exact query without knowing your structure but getting a whole tables worth of data every time is unscalable
I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }
I'm having a little problem with the codes given below. When I'm using the name="staff_number[]" then it insert the record with everything ok even if it is already in the database table and when i use name="staff_number" it does check the record and also give me alert box but when insert the record if it is not in the database it stores only the first number of the staff number like the staff no is 12345 it stores only 1. can anyone help in this record i think there is only a minor issue what I'm not able to sort out.
PHP Code:
<select placeholder='Select' style="width:912px;" name="staff_number[]" multiple />
<?php
$query="SELECT * FROM staff";
$resulti=mysql_query($query);
while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['staff_no']?>"><?php echo $row['staff_name']?></option>
<?php } ?>
</select>
Mysql Code:
$prtCheck = $_POST['staff_number'];
$resultsa = mysql_query("SELECT * FROM staff where staff_no ='$prtCheck' ");
$num_rows = mysql_num_rows($resultsa);
if ($num_rows > 0) {
echo "<script>alert('Staff No $prtCheck Has Already Been Declared As CDP');</script>";
$msg=urlencode("Selected Staff ".$_POST['st_nona']." Already Been Declared As CDP");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Insert Query
$st_nonas = $_POST['st_nona'];
$t_result = $_POST['st_date'];
$p_result = $_POST['remarks'];
$arrayResult = explode(',', $t_result[0]);
$prrayResult = explode(',', $p_result[0]); $arrayStnona = $st_nonas;
$countStnona = count($arrayStnona);
for ($i = 0; $i < $countStnona; $i++) {
$_stnona = $arrayStnona[$i];
$_result = $arrayResult[$i];
$_presult = $prrayResult[$i];
mysql_query("INSERT INTO staff(st_no,date,remarks)
VALUES ('".$_stnona."', '".$_result."', '".$_presult."')");
$msg=urlencode("CDP Staff Has Been Added Successfully");
echo'<script>location.href = "cdp_staff.php?msg='.$msg.'";</script>';
}
Your $_POST['staff_number'] is actually an array.
So you have to access it like $_POST['staff_number'][0] here, 0 is a index number.
If the name of select is staff_number[] then $prtCheck will be a array so your check query must be in a loop to make sure your check condition.
if the name is staff_number then the below code is fine.
The answer of amit is right but I will complete it.
Your HTML form give to your PHP an array due to the use of staff_number[] with [] that it seems legit with the "multiple" attribute.
So you have to loop on the given values, you do it with a for and a lot of useless variables without really checking it. From a long time, we have the FOREACH loop structure.
I could help you more if i know what is the 'st_nona', st_date' and 'remarks' values.
According to your question you are getting difficulty in storing the data. This question is related to $_POST array.
Like your question we have selected following ids from the select : 1,2,3,4
It is only storing 1.
This is due to you have not used the loop when inserting the data.
Like below:
<?php
foreach($_POST['staffnumber'] as $staffnumber){
$query=mysql_query("select * from staff where staff_number =".$staffnumber);
if(mysql_num_rows($query)>0){
//action you want to perform
}else{
//action you want to perform like entering records etc. as your wish
}
}
?>
And I would like to suggest you that use the unique keys in database for field and use PHP PDO for database, as it is secure and best for OOPs.
Let me know if you have any queries.
I am unable to understand why I am unable to use echo statement properly here.
Link which passes get value to script
http://example.com/example.php?page=2&hot=1002
Below is my script which takes GET values from link.
<?php
session_start();
require('all_functions.php');
if (!check_valid_user())
{
html_header("example", "");
}
else
{
html_header("example", "Welcome " . $_SESSION['valid_user']);
}
require('cat_body.php');
footer();
?>
cat_body.php is as follows:
<?php
require_once("config.php");
$hot = $_GET['hot'];
$result = mysql_query( "select * from cat, cat_images where cat_ID=$hot");
echo $result['cat_name'];
?>
Please help me.
mysql_query returns result resource on success (or false on error), not the data. To get data you need to use fetch functions like mysql_fetch_assoc() which returns array with column names as array keys.
$result = mysql_query( "select
* from cat, cat_images
where
cat_ID=$hot");
if ($result) {
$row = mysql_fetch_assoc($result);
echo $row['cat_name'];
} else {
// error in query
echo mysql_error();
}
// addition
Your query is poorly defined. Firstly there is not relation defined between two tables in where clause.
Secondly (and this is why you get that message "Column 'cat_ID' in where clause is ambiguous"), both tables have column cat_ID but you did not explicitly told mysql which table's column you are using.
The query should look something like this (may not be the thing you need, so change it appropriately):
"SELECT * FROM cat, cat_images
WHERE cat.cat_ID = cat_images.cat_ID AND cat.cat_ID = " . $hot;
the cat.cat_ID = cat_images.cat_ID part in where tells that those two tables are joined by combining rows where those columns are same.
Also, be careful when inserting queries with GET/POST data directly. Read more about (My)Sql injection.
Mysql functions are deprecated and will soon be completely removed from PHP, you should think about switching to MySQLi or PDO.
I am trying to grab ad code from my database and echo it on to the page, but for some reason it is not showing up?
$getad = ("SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ");
while($rows = mysql_fetch_array($getad))
{
$code = $rows['code'];
}
$ad1 = $code;
later down the page i print it like this.
<?php print $ad1 ?>
I think your problem is that you don't actually execute the query, you just have saved it in a variable ($getad) and then try to do a fetch af an array containing a string as I see it. If I remeber correctly you have to save you query in a variable, as you did, and then type
$getad = "SELECT * FROM ads WHERE place='non-mobile' AND who='adbrite' ";
$q = $db->query($getad);
// generate results:
while ($q->fetchInto($row)) {
//display or store
}
You should also include checks, for example that this code has extracted at least one row, or that database connection is working, etcetera.