How select rows from database mysql with foreach? - php

For ex. adress page test.php?prid=4477535
Code page test.php
function query($query) {
$database = 'test';
$host = 'test';
$username = 'test';
$password = 'test';
$link = mysql_connect($host,$username,$password);
if (!$link) {
die(mysql_error());
}
$db_selected = mysql_select_db($database);
if (!$db_selected) {
die(mysql_error());
}
$result = mysql_query($query);
mysql_close($link);
return $result;
}
$product_idn=$_GET['prid'];
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
foreach ($select_image as $row)
{
$select_image_array[]=$row->image;
}
print_r ($select_image_array);
receives a request
SELECT *
FROM products_images
WHERE `product_idn` = '4477535'
If make select from phpmyadmin i have 10 rows.
But if i use test.php?prid=4477535 i see empty page.
print_r ($select_image_array) not show array.
Tell me please why i see rows with phpmyadmin and not see rows with script?

Like the other said, you are prone to SQL injection since you don't serialize your input, but to fix your code, use this:
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
while($data = mysql_fetch_assoc($select_image))
{
echo $data['image'];
}

You are doing it wrong.
You have to fetch the resource (mysql_query returns a resource) into an array, and the keys of the array will be the names of the rows returned from your query.
$product_idn=$_GET['prid'];
$select_image = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'") or die(mysql_error());
while($fetch=mysql_fetch_assoc($select_image))
{
echo $fetch['image'];
}
print_r ($select_image_array);
BTW, You have a security hole here - SQL Injection.

Test the following
$result = query("SELECT * FROM products_images WHERE `product_idn`='$product_idn'")
$select_image = mysql_fetch_assoc($result);
var_dump($select_image);
for more information look at http://se2.php.net/mysql_query

You just
echo $row->image;
Never initialize $select_image_array

print_r ($select_image_array); won't show anything because there is no $select_image_array defined. Did you mean print_r ($select_image);?
Is query() a function you've defined? If not and you don't have errors on you are likely to see nothing.
You also need to sanitize your SQL. Simplest method for now since it's an integer:
$product_idn=(int)$_GET['prid'];

Related

Get all values in column MySQL and count PHP

I try to create a function that will get all values (int) in specific column in my database (MySQL), and create the total of all values. I have an error: Resource id #12
This is my function:
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) FROM articles");
return $result;
}
And this my declaration:
<h4><?php echo vuesCours(); ?></h4>
Thank you in advance for your response.
This is not error just you have to do one thing more after query, so try to replace following code and try again.
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) as total FROM articles");
$row = mysql_fetch_array($result);
return $row['total'];
}
It may help you.
you need to return not results but the value of row. something like this:
function vuesCours() {
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT SUM(views) as total FROM articles");
$row = mysql_fetch_array($result)
return $row['total'];
}
hope this helps.
$con = mysql_connect("localhost","root","root");
mysql_select_db("myDataBase", $con);
$result = mysql_query("SELECT views FROM articles");
$sum=0;
while($row=(mysql_fetch_row($result)))
{
$sum=$sum+$row['views'];
}
echo $sum;
1) i have just changed the select query
2)we have result set of query in $result
3)mysql_fetch_row will return result row as an enumerated array
from which you can access
particular column by it's name or by giving id into subscript brackets in a line $sum=$sum+$row[index/name of column];

Count number of rows in SQL database

I am trying to view how many rows there are based on a SQL query using PHP.
I seem to be able query the database and return fields from a row but can't seem to find out how many rows there are based on the same query.
<?php
$host = 'localhost';
$user = 'MyUsername';
$pass = 'MyPassword';
$database = 'MyDatabase';
$con=mysqli_connect($host,$user,$pass ,$database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
mysqli_close($con);
?>
All it returns is the text Rows on the screen, without the number of rows at the start.
Like I said, this same query works and returns a value if I try and select a row using:
while($row = mysqli_fetch_array($result))
{
echo $row["test"];
}
Anyone know why it won't return the number of rows?
You are using MySQLi. Because of you don't have a mysql query, mysql_num_rows doesn't return desired value.
You have to replace your mysql function with mysqli equal:
$num_rows = mysqli_num_rows($result);
You are using Mysqli to you should use mysqli_num_rows
$result = mysqli_query($con,"SELECT * FROM MyTable WHERE test='123' AND test2='456'");
$num_rows = mysqli_num_rows($result);
If you want only count then you can directly use count(*) like this:-
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result;
I'll do some thing like this:
$result = mysqli_query($con,"SELECT COUNT(*) FROM MyTable WHERE test='123' AND test2='456'");
echo $result

Get result out of query [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How do i “echo” a “Resource id #6” from a MySql response in PHP?
I am looking for the result out of a query, but it keeps giving me resource id #3.
The following is my code.
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
print_r($typeResult);
What step am I missing here?
You need to fetch the result. All you're doing is sending the query.
Be aware that if you are writing new code, you should use mysqli_ or PDO functions as your query is vulnerable to SQL injection and mysql_ functions are being deprecated. Hesitantly, below is a sample for mysql_fetch_assoc.
<?php
$sql = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$result = mysql_query($sql);
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[sellingid];
}
mysql_free_result($result);
?>
Reference
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
$row = mysql_fetch_array($typeResult);
print_r($row);
More clear hint - use MySQLi class/functions, read this:
http://lt1.php.net/manual/en/mysqli-result.fetch-assoc.php
or if you like OOP approach more then
http://lt1.php.net/manual/en/mysqli-result.fetch-object.php
You are not actually fetching the results of your query. Below are two examples that use WHILE loops to fetch the results as rows. You can then grab the column values and work with them.
Incorrect and depreciated method, but working:
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$typeResult = mysql_query($type);
// for each row
while ($row = mysql_fetch_array($typeResult)) {
// grab the columns
$value = $row['column_name'];
}
I would recommend using MySQLi or PDO like to following (MySQLi):
$mysqli_connection = new mysqli("hostname", "username", "password", "database");
$type = "SELECT `sellingid` FROM `ticket` WHERE `ticketid` = $_GET[ticketid]";
$res = $mysqli_connection->query($type);
while($row = $res->fetch_array(MYSQLI_ASSOC)) {
$value = $row['column_name'];
}
$res->free();
$mysqli_connection->close();

Using php to access mysql, how can I get the query result which is only a number?

For example, for some queries like SELECT MAX(field), the query result is usually only a field value, rather than returning rows to you.
Now the field of the value I wanna get is integer type.
As I'm a beginner of php, how can I get that value from the query result?
As I do the following
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo $result;
Then nothing is echoed out.
I have check the db connection made by mysqlconnect, and it's got no problem.
And I tried this query in MySQL at phpMyAdmin, then the query is what I want, too?
So why would it be like that, and any solution?
Thanks!
You will always retrieve rows back from an SQL query, even if there's only one row with one field. You can directly retrieve a specific field of a specific row using mysql_result:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
echo mysql_result($result, 0, 0);
$query = "SELECT MAX(stringid) as val FROM XMLString";
$result = mysql_query($query, $link);
$rows = mysql_num_rows($result);
if($rows > 0) {
$rstAry = mysql_fetch_array($result);
echo $rstAry['val'];
}
Try This
mysql_query is not printing results. Maybe try this:
echo mysql_result($result);
You are not getting any result because mysql_query returns a database object.
You will need to process this "database object" using mysql_fetch_array. This command 'fetches' an array out of a MySQL "database object". The array you are fetching is the rows your query produced. In your case, it is just one row.
Here is the code:
This step sets your query:
$query = "SELECT MAX(stringid) as val FROM XMLString";
This step will run your query, and return the database object:
$result_database_object_whatever = mysql_query($query, $link);
This step will process the database object, and give you an array of the queried rows:
$result_array = mysql_fetch_array($query, $link);
This step will echo the first row returned by your query:
echo $result_array[1];
You can do something like this:
$query = "SELECT MAX(stringid) FROM XMLString";
$result = mysql_query($query, $link);
$fetch = mysql_fetch_assoc($result);
echo $fetch['stringid'];
The mysql_fetch_assoc() function retrieves the data in an associative array.
Would it help to give the max a name you could reference? Also ifyou think there's syntax errors you could just add the error to help clarify.
$query = "SELECT MAX(stringid) as maxNum FROM XMLString";
$result = mysql_query($query, $link) or die(mysql_error());
echo $result;

Creating a variable by pulling a value from a MySQL database

I am using a MySQL table called "login" that includes fields called "username" and "subcheckr."
I would like to run a PHP query to create a new variable equal to "subcheckr" in the table where "username" equals a variable called $u. Let's say I want to call the variable "$variable."
How can I do this? The query below is what I have so far.
Thanks in advance,
John
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
I don't know if I understood correctly but if:
Just do something like this.
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
In case you don't know, your query is vulnerable for SQL injections. Use something like mysql_real_escape() to filter your $u variable.
Is this what youa re looking for?
$result = mysql_query($sqlStremail);
$row = mysql_fetch_assoc($result);
$subcheckr = $row['subcheckr'];
$sqlStremail = mysql_query("SELECT subcheckr FROM login WHERE username = '$u'");
$result= mysql_fetch_array($sqlStremail);
$some_variable = $result['subcheckr']; // the value you want
You can do:
// make sure you use mysql_real_escape to escape your username.
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
// run the query.
$result = mysql_query($sqlStremail );
// See if the query ran. If not print the cause of err and exit.
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
// if query ran fine..fetch the result row.
$row = mysql_fetch_row($result);
// extract the field you want.
$subcheckr = $row['subcheckr'];
You can write
$sqlStremail = "SELECT subcheckr FROM login WHERE username = '".mysql_real_escape($u)."'";
$result = mysql_query($sqlStremail );
if (!$result) {
die 'Could not run query: ' . mysql_error();
}
$row = mysql_fetch_row($result);
$subcheckr = $row['subcheckr'];
$variable = array_pop(mysql_fetch_row(mysql_query("SELECT subcheckr FROM login WHERE username = '$u'")));
Only if username is unique

Categories