How to retrieve values from a database? - php

I want to get variable data "$b ,$d, $f,$h" from database and then calculate it. Here is my example:
<?php
$host="localhost";
$username="root";
$password="root";
$db_name="cbrteh"
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$b= mysql_query("SELECT bobot FROM atribut where id= 1");
($row = mysql_fetch_assoc($b));
$row["bobot"];
$d= mysql_query("SELECT bobot FROM atribut where id= 2");
($row = mysql_fetch_assoc($d));
$row["bobot"];
$f= mysql_query("SELECT bobot FROM atribut where id= 3");
($row = mysql_fetch_assoc($f));
$row["bobot"];
$h= mysql_query("SELECT bobot FROM atribut where id= 4");
($row4 = mysql_fetch_assoc($h));
$row["bobot"];
$calc = $b+$d+$f+$h;
echo $calc;
<?
The values in the database are 50,50,50,50 but the result is 22. Why is this?

The line below every query string is wrong
($row = mysql_fetch_assoc($b));
$row["bobot"];
Because you are not storing the result anywhere.The correct way to get the values should be:
if(count($res=mysql_fetch_assoc($b))>0)$_b=$res[0]['bobot'];
(if returning result has at least one row, return the value to $_b variable)
Mind that $b is being used to store the query result, not the value you get from it.
Then you sum the results like this:
$calc = $_b+$_d+$_f+$_h; and that's all.

It seems you could do all the work in your database:
$query = mysql_query(
"SELECT SUM(bobot) AS summation FROM atribut where id IN (1,2,3,4)"
);
$row = mysql_fetch_assoc($query);
$calc = $row['summation'];
I've removed the unnecessary brackets around the assignment to $row, and of course I've replaced four separate lookups with just one. Since I've used the grouping function SUM, I have aliased it as summation so it is easy to retrieve from the row.

Related

php display data from database with char search

I am trying to display a record from a mysql database depending on the char posted from a form input. But I can't get this to work.
My HTLM code is below
<form action='headcode_Db_connect.php' method='POST'>
<input type="text" name="headcode" value="" maxlength="2">
</form>
My PHP code
<?php
$headcode = $_POST['headcode'];
echo $headcode;
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="789852"; // Mysql password
$db_name="work"; // Database name
$tbl_name = "headcodes";
// Connect to server and select database.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Retrieve all data from the table
$sql = "SELECT * FROM $tbl_name WHERE LIKE '%$headcode%'";
$result1 = mysql_query($sql, $link);
// if successfully, displays message "Successful".
if($result1){
$connect = "connected";
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
while ($row = mysql_fetch_assoc($result1)){
$number = $row['number'];
}
echo $number;
?>
I keep getting an error. The data being sent will be 1A or 2A and should display the number from the database for this record. If I change WHERE LIKE '%$headcode%'"; to WHERE headcode = '1A'"; I get a result of 17 which is correct. So how can I use the POST variable to give this result.
WHERE LIKE '%$headcode%'"
If you searched for at (for example), the following would all match:
at, bat, cat, rat
However , if you lose the first %, It must start with your search term letters
WHERE LIKE '$headcode%'"
which would return all words beginning with at. Hope this helps!
I got it working with the below code.
<?php
$headcode = $_POST['headcode'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="789852"; // Mysql password
$db_name="work"; // Database name
$tbl_name = "headcodes";
// Connect to server and select database.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
//Retrieve all data from the table
$sql = "SELECT * FROM $tbl_name WHERE headcode = '$headcode'";
$result1 = mysql_query($sql, $link);
if($result1){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
while ($row = mysql_fetch_assoc($result1)){
$number = $row['number'];
}
echo $number;
?>

Can't echo array properly

My table in the database contains 3 columns that all has qwe for a username and have the respective dates of January, February and March but when I try to echo them it only displays January. I'm trying to get them all into a drop down list but I can't get past this so I have to make sure I get all of these dates before I put them elsewhere.
{
$con=mysqli_connect('localhost','root','') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request="SELECT date FROM mytable WHERE username='qwe'";
$result=mysqli_query($con, $request);
$fetch=mysqli_fetch_assoc($result);
echo $fetch['date']; echo "<br>";
print_r($fetch);
}
You are missing loop, data come up. You can see when you are printing data using print_r($fetch), use loop to show one by one.
And also try to don't use user input directly in query before checking mysql injection. like you have putted username='qwe' if username is user input then use it like this directly in query Suggestion for query
$request = "SELECT date FROM mytable WHERE username=".mysql_real_escape_string('qwe');
and your with loop try this,
$con = mysqli_connect('localhost', 'root', '') or die(mysqli_error());
mysqli_select_db($con, 'useddates') or die("cannot select DB");
$request = "SELECT date FROM mytable WHERE username='qwe'";
$result = mysqli_query($con, $request);
print_r($fetch);
while ($fetch = mysqli_fetch_assoc($result)) {
echo $fetch['date'];
echo "<br>";
}
?>

Output database text value into div

I am trying to output values saved in my database into a div field, however the data does not seem to come out, could anyone explain to me why?
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT from `posts`");
$num=mysql_numrows($result);
$i=0;
while ($i < $num) {
echo $result[$i];
$i++;
}
?>
</div>
Above is the code I have inside the div tag. So my question why does my echo not work?
This is not the way to do that, you may use like this:
//$result=mysql_query("SELECT from `posts`"); <- this query is wrong.
if ($result = mysql_query("SELECT * FROM posts"))
{
$num=mysql_num_rows($result);
while ($row = mysql_fetch_assoc($result)) {
echo $row['key']; // <- you must set the field name of your query here
}
}
else // This if will show you when any query error is thrown.
{
echo mysql_error();
}
Your original query is wrong. You may get an error because SELECT FROM is not valid. You have to specify a list of fields, a function or * to get all fields of the table.
The you may use mysql_fetch_assoc(), mysql_fetch_row() or mysql_fetch_array() in order to fetch the received data from the query.
Plus, I have added an if in your query command in order to get any mysql error thrown in your query execution. Using that you'll never be confuse about what happened here.
Hope it helps.
UPDATE: As #SpiderLinked said(Thank you dude), mysql_numrows() does not exists. You have to use mysql_num_rows() to get query result count.
"SELECT from `posts`"
is not a valid query.
This would be:
"SELECT * FROM `posts`"
Also the following won't pull any results from your database:
while ($i < $num) {
echo $result[$i];
$i++;
}
You would need to loop around the results as you fetch them:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field'];
}
try this....
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
$result=mysql_query("SELECT * FROM posts");
$num=mysql_numrows($result);
if($num>0) {
echo $num." rows returned";
while ($row = mysql_fetch_assoc($result)) {
echo $row['key'];
}
} else {
echo "No Rows Returned";
}
?>
</div>
There are several errors with your code...first....you do not give the result of the query to any variable...second...your query is wrong...third... there is no such function as mysql_numrows()....here is an example of what it should look like:
<div>
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="Database"; // Database name
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$result=mysql_query("SELECT * FROM posts") or die (mysql_error()); //added die for debugging purposes
while ($num=mysql_fetch_array($result)) {
echo $num['COLUMN NAME HERE!'];
}
?>
Also...please stop using mysql_ while it is deprecated...

Flipping active = -1 to active = 1

Built this, and executed it, but the database in phpmyadmin has no changes... what am I missing?
Active is obviously a column name in each table... there are 107 tables I need to flip.
Thanks.
<?php
mysql_connect("localhost", "root", "789feRNSHB")or die("cannot connect to server");
mysql_select_db("core")or die("cannot select db");
$sql = "SHOW TABLES FROM core";
$result = mysql_query($sql);
$arrayCount = 0;
while($row = mysql_fetch_row($result)) {
$tableNames[$arrayCount] = $row[0];
$arrayCount++; //only do this to make sure it starts at index 0
}
//print_r($tableNames);
for($i=0;$i<sizeof($tableNames);$i++){
$table= $tableNames[$i];
echo $query = "UPDATE ".$table." SET Active=1 where Active=-1";
echo'>>'.mysql_query($query).'<br>';
}
?>
Explicitely call the mysql_error() function to see what happens. Example in http://ca2.php.net/manual/en/function.mysql-error.php.

Problem with max SQL function

I have this code in PHP
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
then the output be:
The max num is this is it
hh
Why didn't the query get the max number?
The table is called info and it has these fields, ID, num, title, description, and answer.
After editing:
I tried my query in MySQL and it works fine!
"SELECT MAX(num) FROM info"
and this is my complete code if it can help:
<?php
$answer=$_GET["answerbox"];
$ID=$_GET["TheID"];
$host="localhost";
$username="root";
$password="";
$db_name="game";
mysql_connect("$host","$username","$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
$sql="SELECT * FROM info WHERE ID=".$ID;
$query = mysql_query($sql) or die(errorquery);
$row = mysql_fetch_array($query);
$trueanswer = $row['Answer'];
$num=$row['num'];
if ($num<$maxnum)
{
$numto= $num +1 ;
echo "<br>".$maxnum."hh";
}
?>
Then the code will be
$max="SELECT MAX(num) as num FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_assoc($maxquery)) {
echo "The max num is ". $row['num']."this is it";
}
The column you are looking for in the result set is NOT called num. Try print_r($row); to see what the array indices are, or give it an alias, e.g.
$max="SELECT MAX(num) AS max_num FROM info";
...
echo "The max num is ". $row['max_num']
Here is another and simpler way:
$query="SELECT MAX(num) FROM info";
list ($max) = mysql_fetch_row(mysql_query($query));
print ($max);
num field in your database has to be a numeric datatype (i.e. int, float etc) in order for this to work properly.
It's because your query returns a scalar value, not an array. $maxquery is the value you want to get.
I recommend checking your query against the database before try running it with PHP.
Run your query within the MySQL query window then analyse the output. That way you can concentrate on the query without the PHP getting in the way.
Once you've done that modify the question so that we can see the query that's actually being run.
The query is looking fine. Please inspect your code of getting data from the result set step by step.

Categories