I have this code:
<?php
$con = mysql_connect(DB_HOST, DB_USER, DB_PASS);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(DB_NAME, $con);
$result = mysql_query("SELECT SUM(colname) FROM profits");
$total = reset (mysql_fetch_assoc($result));
mysql_close($con);
echo $total;
?>
And its outputting an Resource id #5. Any help? Thanks in advance!
Don't use reset() like that - if you need a single value, just use list():
$result = mysql_query("SELECT SUM(colname) FROM profits");
list($total) = mysql_fetch_array($result);
reset() does not work as you expect on associative arrays: https://bugs.php.net/bug.php?id=38478
You're trying to echo an associative array with echo $total;. Instead just echo the first (and probably only based on your query) item.
$row = mysql_fetch_assoc($result);
echo $row[0];
Related
i have SQL query :
SELECT countryCode FROM itins_countries WHERE (itinID = 5);
$countriesIndex = mysql_fetch_array($countriesQuery);
now, in another art of my code I would like to run on the "$countriesIndex" and print all the values it contain ("countryCode");
how can i do that?
while($row = mysql_fetch_array($countriesQuery)){
echo $row['column_name'];
///same for other columns
}
you can use the while loop to loop until all the array element has been printed
try this....
echo "<pre>";print_r($countriesIndex);
mysql_connect is deprecated...you can use mysqli_connect.
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno($mysqli)) {
trigger_error('Database connection failed: ' . mysqli_connect_error(), E_USER_ERROR);
}
mysqli_set_charset($mysqli, "utf8");
$sql = "SELECT countryCode FROM itins_countries WHERE (itinID = 5)";
$result = mysqli_query($mysqli, $sql);
$countries = [];
while($row = $result->fetch_assoc())
{
$users_arr[] = $row;
}
$result->close();
print_r($users_arr);
I have a SQL table (modules) with two columns (id, name). Now I can retrieve the rows from this through a PHP script but what I want is to use the value of id as the key, and the value of name as the value, in a multidimensional array. Then I want to be able to encode those into a JSON, retaining the relationship between key/value. I've muddled something together but it returns null.
the relevant code from index.php
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response["module"]["mod1"] = $modules[$mod1];
$response["module"]["mod2"] = $modules[$mod2];
$response["module"]["mod1name"] = $modules[$mod1]["name"];
$response["module"]["mod2name"] = $modules[$mod2]["name"];
echo json_encode($response);
The function from DB_Functions.php
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_error());
}
// selecting database
mysqli_select_db($con, DB_DATABASE) or die(mysqli_connect_error());
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[] = $row;
}
// return user details
return mysqli_fetch_array($arr);
close();
}
I've looked around but I'm just not 'getting' how the query return is then broken down into key/value for a new array. If someone could ELI5 I'd appreciate it. I'm just concerned with this aspect, it's a personal project so I'm not focusing on security issues as yet, thanks.
You are pretty well there
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$query = "SELECT * FROM modules WHERE id= '$mod1' OR id='$mod2'";
$result = mysqli_query($con, $query);
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
And call it and then just json_encode the returned array
$mod1 = $core["module1"];
$mod2 = $core["module2"];
$modules = $db->getModulesById($mod1, $mod2); //module names & ids
$response['modules'] = $modules;
echo json_encode($response);
You should really be using prepared and paramterised queries to avoid SQL Injection like this
public function getModulesById($mod1, $mod2) {
require_once 'include/Config.php';
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
// Check connection
if (!$con) {
die("Connection error: " . mysqli_connect_error());
}
$sql = "SELECT * FROM modules WHERE id= ? OR id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param('ii', $mod1, $mod2);
$stmt->execute();
$result = $stmt->get_result();
$arr = array();
while($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
// here is wrong
//return mysqli_fetch_array($arr);
// instead return the array youy created
return $arr;
}
mysqli_fetch_array requires the result of a mysqli_query result. Passing the constructed array to mysqli_fetch_array() is not going to work.
If you want to have a specific value from a row to use as its key, you can't resolve this with any mysqli_* function. You could however construct it yourself:
while($row = mysqli_fetch_assoc($result)) {
// process each row
//each element of $arr now holds an id and name
$arr[$row['id']] = $row;
}
mysqli_close($con);
return $arr;
You should close the connection before returning the result, code positioned after a return will not be executed.
This question already has answers here:
Deprecated: mysql_connect() [duplicate]
(12 answers)
Closed 6 years ago.
How can I make this query or script work properly with having these deprecated errors I am getting when using Wamp I am not getting the errors while using Xampp though. The errors or warning i'm getting is on this pic
this is my php script
<?php
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT gender as gender_occupation, COUNT(*) as total FROM hostel_blocks GROUP BY gender");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysql_close($con);
?>
when i changed some connection code i got a blank page.
PHP mysql was deprecated in PHP 5.5 and removed starting PHP 7
You should move to mysqli instead.
Your code using mysqli would look like this:
<?php
$con = mysqli_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db( $con, "db");
$result = mysqli_query($con, "SELECT gender as gender_occupation, COUNT(*) as total FROM hostel_blocks GROUP BY gender");
$rows = array();
while($r = mysqli_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Ok so now I have this code where I'm retrieving data from db table:
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_row($query);
var_dump($row);
echo 'Connected successfully';
mysql_close($link);
?>
So in this table I have many rows and each has a "serial_number" column.... now what I'm trying to do is, get the row with the SPECIFIC serial_number (which I have as a variable)...
so for example
# serial_number
1 AB1
2 AB2
3 AB3
4 AB4
5 AB5
and for example I have a variable $product = AB2
How can I GET from the database only the row that has "serial_number" = $product=AB2 ?
Please can somebody help me with this. Thank you
Use MySQL WHERE Clauses like that :-
$query = mysql_query("select * from machine where serial_number = '$product'", $link);
Your Query work like that :-
select * from machine where serial_number = 'AB2'
Well it is actually not hard you just need to know what to do here. So as Rahautos said, you can use the WHERE clause.
Your code(fixed):
<?php
$link = mysql_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysql_select_db("funkireport", $link);
$query = mysql_query("select * from machine where serial_key='SERIAL KEY'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
?>
or instead you can use a form, input the key in the text field and get the results out with automation:
<?php
if(isset($_POST['submit']) {
$link = mysqli_connect('funki.fresh-tech.it', 'userns3e', '2w3rwrtwd');
$db = mysqli_select_db("funkireport", $link);
$key = $_POST['key']
$query = mysql_query("select * from machine where serial_key='$key'", $link);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$row = mysql_fetch_array($query);
echo $row['serial_key'];
mysql_close($link);
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label>Key:</label>
<input type="text" name="key">
<input type="submit" name="submit">
</form>
I have been trying for the past while to echo out the result of a a MySQL query in PHP. I can't seem to get it to work so I am a bit lost. I know for a fact that the query works as I have done it in PHPMYADMIN and it is working fine, however whenever I load the webpage, nothing is outputted. For the purposes of this question I have generalized the things in the query as I obviously don't want anyone accessing my database. This is what I have tried:
<?php
$connect = mysql_connect('host', 'user', 'password', 'dbname');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('dbname')) {
die('Could not select database: ' . mysql_error());
}
$result = mysql_query('SELECT SUM(row name) FROM `table`');
if (!$result) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result);
mysql_close($connect);
?>
I look forward to your replies.
mysql_result need the second parameter (The row number from the result that's being retrieved).
echo mysql_result($result, 0);
you have to change
echo mysql_result($result);
by
echo mysql_result($result,0);
or you can use
print_r(mysql_fetch_assoc($result));
Try this
echo mysql_result($result,0);
For more information, please give a look on http://www.php.net/mysql_result
or you can use mysql_fetch_row instead of mysql_result.
$row = mysql_fetch_row($result);
echo $row[0];
You may use this following format:
Give your Sql command like this:
$result = mysql_query('SELECT SUM(row name) as new_column_name FROM `table`');
then use this loop
while($fetched_values = mysql_fetch_array($result)){
echo $fetched_values['new_column'];
}
In your mysql_connect you have provided 4 parameters. it accepts 3 params
host, username and password. dbname is given inside mysql_select_db
as you can see from official docs. So remove the 4th param from mysql_connect function.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
http://php.net/function.mysql-connect
$db_selected = mysql_select_db('foo', $link);
http://www.php.net/manual/en/function.mysql-select-db.php
but these mysql_* function will be deprecated use mysqli instead.
pass a row number as second parameter in mysql_result
echo mysql_result($result, 1);
or
use print_r(mysql_fetch_array($result));
where $result is your result resource
if you have any doubt you may refer my following example program.
<?php
$connect = mysql_connect('localhost', 'user_name', 'password', 'db_name');
if (!$connect)
{
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name'))
{
die('Could not select database: ' . mysql_error());
}
$row = mysql_query('SELECT (Tamil+English+Maths) as total FROM table_name');
if (!$row)
{
die('Could not query:' . mysql_error());
}
while($fetched_row = mysql_fetch_array($row)){
echo $fetched_row['total'];
}
mysql_close($connect);
?>
here Tamil,English and Maths are the column values of my table