Ok so I don't know what the hell is going on I'm just trying to list all the data in a table and it's just not working I have tried a few different ways and I'm not getting any error messages and I have been over the syntax many times.
Here is the code:
// Connect to database
$dbc = mysql_connect("localhost", "root");
if (!$dbc)
die("Could not connect" . mysql_error());
// Select database
$dbc_dbselect = mysql_select_db( "contactmanager", $dbc );
if (!$dbc_contactmanager)
die("Could not connect: " . mysql_error());
// Query database
$query = "SELECT * FROM contacts ORDER by name";
$result = mysql_query($query);
// start a table tag in the HTML
echo '<table>';
// Create a loop to loop through results
while($row = mysql_fetch_array($result)){
// Print the results
echo '<tr>'.'<td>'.$row['Name'].'</td>'.'<td>'.$row['Address'].'</td>'.'<td>'.$row['Phone'].'</td>'.'<td>'.$row['Mobile'].'</td>'.'<td>'.$row['Mobile'].'</td>'.'</tr>';
}
echo "</table>"; //Close the table in HTML
mysql_close($dbc);
And this is the output result in firefox:
'; //Create a loop to loop through results while($row = mysql_fetch_array($result)){ echo ''.''.$row['Name'].''.''.$row['Address'].''.''.$row['Phone'].''.''.$row['Mobile'].''.''.$row['Mobile'].''.''; //$row['index'] the index here is a field name } echo ""; //Close the table in HTML mysql_close($dbc); ?>
Database and table
I think you are missing the third parameter i.e: password
$dbc = mysql_connect("localhost", "root", "");
^----Here
it should be:
mysql_select_db( "contactmanager", $dbc );
Provide password as a third parameter whatever it is set on your system in double quotes
$dbc = mysql_connect("localhost", "root", "<DBMS_PASSWORD>");
if not set , leave double quotes empty ("").
Related
sorry to bother you all but I'm really struggling with this one:
I connect to my database fine and then I try the following mysql statements:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
However, a few lines later when I try :
echo $answer1;
I'm given only nulls :(
Can anyone give me any suggestions please?
edit:
SQL logins:
mysql_connect("correct", "username", "password");
mysql_select_db("dbname") or die(mysql_error());
everything you did is right you have just to fetch the data like this:
$query1 = "select row1 from mydatabase where row2 = $Name ";
$answer1 = mysql_query($query1);
while($data= mysql_fetch_array($answer1)){
echo $data['row1'];
}
And this is a complet answer, i adjust it as you need ;)
<?php
//Connect to your database
$con=mysqli_connect("db_hostname","db_user","db_password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Value of the row to select
$row2 = 'some value';
//Make select query
$result = mysqli_query($con, "SELECT row1 FROM MyTable WHERE row2='$row2'");
//Fetch datas
while($row = mysqli_fetch_array($result))
{
echo $row['row1'];
echo "<br>";
}
//Close database
mysqli_close($con);
?>
Good Luck :)
Try using MySQLi_* instead MySQL_* functions and pass the connection variable to the function calls.
If this doesn't work then you might want to try some further debugging by enabling all error reporting and dumping the global scope.
<?php
error_reporting(E_ALL); // Show all errors & warnings
$conn = mysqli_connect("server", "username", "password");
mysqli_select_db($conn, "dbname") or die(mysql_error());
$sql1 = "SELECT `row1` FROM `mydatabase` WHERE `row2` = '".$Name."';";
$query1 = mysqli_query($conn, $sql1);
$answer1 = mysqli_fetch_assoc($query1);
var_dump($GLOBALS); // Dumps all variables in the global scope
?>
add this after $answer1= mysql_query($query1);
while ($row = mysql_fetch_assoc($answer1)) {
// echo data
echo $row['row1'];
}
At the moment I am displaying only the first ID sorted ascending.
I have to display multiple ID results, from the same table. How would I accomplish this task?
<?php
$dbhost ='localhost';
$dbuser =‘user’; $dbpass =‘pass’;
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn){
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM table_name ORDER BY id ASC LIMIT 0, 1';
mysql_select_db('database_name’);
$retval = mysql_query($sql, $conn);
if(!$retval){
die('Could not get data: ' . mysql_error());
}
?>
<?php while($row = mysql_fetch_assoc($retval))
{echo "{$row[‘full_name’]}”.”
{$row[‘telephone']}"."
{$row[‘email’]}”;}
mysql_close($conn);
?>
All you have to do is change the LIMIT 1 to whatever number you want, or just remove it. Removing it would look like:
$sql = 'SELECT * FROM table_name ORDER BY id ASC'
why do you have a limit if you want all the ids to be displayed?
you can use a while loop in your script
for eg:
while($row = mysql_fetch_assoc($test)){
<div id="'.$row['id'].'">'.$row['id']'.</div>;
}
which will output:
<div id="my id 1">my data 1</div>
<div id="my id 2">my data 2</div>
<div id="my id 3">my data 3</div>
.
.
.
and so on
your modified code that outputs the data in different divs
<?php
$db = mysqli_connect("localhost", "user", "pass" ,"database name") or die("Could not connect database");//keep it in one line and use (mysqli) instead of (mysql) because newer mysql versions donot support (mysql)
$retreive=mysqli_query($db,'SELECT * FROM table_name ORDER BY id');//if youre connection is in another file you need to include the connection variable before the selection line.In this case $db is the connection variable
while($row=mysqli_fetch_array($retrieve))
{ the following code creates a div for each result
echo '<div class="'.$row['fullname'].'">'.$row['fullname'].'</div>';.
echo '<div class="'.$row['telephone'].'">'.$row['telephone'].'</div>';
echo '<div class="'.$row['email'].'">'.$row['email'].'</div>';
}
?>
tried the above code on my test server and it works
I am using php to get records from a mysql database using the following code:
<?php
$username="";
$password="";
$database="";
$hostname="";
$con = mysql_connect($hostname, $username, $password);
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
if(isset($_POST['emp'])){
$emp = $_POST['emp'];
$result = mysql_query("SELECT * FROM contact_log", $con);
echo mysql_num_rows($result);
die();
while($row = mysql_fetch_array($result)){
$emp = $row['emp'];
echo $emp.'<br>';
}
die();
}
mysql_close($con);
?>
This works fine and returns the correct fields. The problem is that if I change the query to
$result = mysql_query("SELECT DISTINCT * FROM contact_log", $con);
or
$result = mysql_query("SELECT * FROM contact_log GROUP BY emp", $con);
no results are returned.
mysql_num_rows does not even return a value which indicates to me that those lines are breaking my code but I am unable to figure out how.
I doubt you want to do a distinct * on your first query. Looking at your code, you probably want:
"SELECT DISTINCT emp FROM contact_log"
And you can get more information about what is going wrong with mysql_error:
mysql_query("select * from table") or die(mysql_error())
Finally, are you sure that $_POST['emp'] is being sent? Put an echo right after that if to make sure. And just so you know, you aren't using the emp POST variable for anything other than a flag to enter that block of code. $emp = $_POST['emp']; is doing absolutely nothing.
I am trying to Build a simple search that first grabbs 'query' from a form passed from a HTML form through the url to this script. Once I run the script I get the output: Resource id #140Resource id #141Resource id #142. Why am I getting this output and what does it mean?
Side note I am just using the "echo" as a way to see the output of each variable.
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$user_id = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
echo $user_id;
$account_id = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
echo $account_id;
$user_name = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
echo $user_name;
?>
This is not the way to print the results. The method mysql_query returns a resource that you have to use within a loop to actually print the results. For instance, loop at the second example in the official doc page.
P.S. $query = $_GET['query']; using this statement you could have Sql injections problems.
Try something similar to this - after first "SELECT" query :
while($user_id_obj = mysql_fetch_object($user_id))
{
echo $user_id_obj->id;
}
The way you implemented leads to SQL Injection Attacks
SQL Injection Attacks Example
This could be possible in two ways.Which is usefull for you is depends on your requirements.
1.if your query contains a single value as a result then following code with changes in your code will be usefull for you.
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$result_user = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
if (!$result_user) {
die('Could not query:' . mysql_error());
}
$user_id=mysql_result($result_user,0); // outputs first user's id
echo $user_id;
$result_accountuser = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
if (!$result_accountuser) {
die('Could not query:' . mysql_error());
}
$account_id=mysql_result($result_accountuser,0); // outputs first accounts_users's account_id
echo $account_id;
$result_account = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
if (!$result_account) {
die('Could not query:' . mysql_error());
}
echo mysql_result($result_account,0); // outputs first accounts's account_name
?>
2.Or your query contains more than one result or more than one rows than following changes in your code will help you
<?php
//connect to database
mysql_connect("localhost", "user", "password") or die("Error connecting to database: " .mysql_error());
mysql_select_db("dataBase") or die(mysql_error());
?>
<?php
$query = $_GET['query'];
// gets value sent over search form
$result_user = mysql_query("SELECT id FROM users WHERE email = '$query'") or die(mysql_error());
while($row=mysql_fetch_array($result_user))
{
$user_id = $row['id'];
echo $user_id;
}
$result_accountuser = mysql_query("SELECT 'account_id' FROM accounts_users WHERE 'user_id' LIKE ('$user_id')") or die(mysql_error());
while($row=mysql_fetch_array($result_accountuser))
{
$account_id = $row['account_id'];
echo $account_id;
}
$result_account = mysql_query("SELECT 'account_name' FROM accounts WHERE 'id' LIKE ('$account_id')") or die(mysql_error());
while($row=mysql_fetch_array($result_account))
{
echo $row['account_name'];
}
?>
What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("some command");
$row = mysql_fetch_array($result);
mysql_close($con);
?>
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);
$total = $row[0];
echo "Total rows: " . $total;
mysql_close($con);
?>
Either use COUNT in your MySQL query or do a SELECT * FROM table and do:
$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";
mysqli_num_rows is used in php 5 and above.
e.g
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
printf("Result set has %d rows.\n",$rowcount);
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
Use COUNT in a SELECT query.
$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);
you can do it only in one line as below:
$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;
use num_rows to get correct count for queries with conditions
$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";
for PHP 5.3 using PDO
<?php
$staff=$dbh->prepare("SELECT count(*) FROM staff_login");
$staff->execute();
$staffrow = $staff->fetch(PDO::FETCH_NUM);
$staffcount = $staffrow[0];
echo $staffcount;
?>
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
$rowcount=mysqli_num_rows($result);
echo "number of rows: ",$rowcount;
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
it is best way (I think) to get the number of special row in mysql with php.
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>
Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php
$sql = "select count(column_name) as count from table";
Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.
PHP Code
// create a function 'cnt' which accepts '$tableName' as the parameter.
function cnt($tableName){
global $conection;
$itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
echo'<h6>'.$itemCount.'</h6>';
}
Then when I need to get the count of items in the table, I call the function like following
<?php
cnt($tableName = 'projects');
?>
In my HTML front end, so it renders the count number
It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.