Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to fetch some records from MySQL view table in my web page by PHP. I am using this following code:
$result="SELECT method,test_name,test_code FROM vtest_ord ORDER BY
test_ord_id DESC";
echo"<table border='1'><thead><tr><th>Method</th><th>Test Name</th><th>Test
Code</th></tr></thead>";
while ($row=$mysql_fetch_assoc($result)) {
echo "<tr><td>";
echo "<td>" . $row['method'] . "</td>";
echo "<td>" . $row['test_name'] . "</td>";
echo "<td>" .
$row['test_code'] . "</td>";
echo "</tr></td>"; }
echo '</table>';
but I am getting this error:
Fatal error: Function name must be a string in
C:\xampp\htdocs\test2\ord_view.php on line 211 Method Test Name Test
Code (table header shows)
You have some problem with the PHP syntax.
mysql_fetch_assoc is a function and you called it like a variable (which means nothing here).
You try to call this function with a string, but you need a ressource, obtain via mysql_query.
You don't need to write multiple echo statement, thanks to the concatenation syntax.
A potential correct code is:
$sql="SELECT method, test_name, test_code FROM vtest_ord ORDER BY test_ord_id DESC";
echo "[Debug] MethodTest NameTest Code";
$result = mysql_query($sql) or exit(mysql_error()); // Display SQL error if raised
while ($row=mysql_fetch_assoc($result)) {
echo $row['method'] . " " . $row['test_name'] . " " . $row['test_code']; echo "";
}
I also advise you to drop mysql_* and use PHP PDO, since the first one is deprecated for years now.
You need basic php logic. you have some serious errors in your code. please try to read basic of programming.
some errors:
1) $mysql_fetch_assoc is not a variable it is a function mysql_fetch_assoc(); you can not use $ in this name.
2) you need to execute query first then you can fetch.
$link = mysql_connect('host_name','db_user_name','db_password'); //fill correct credentials
mysql_select_db('your_db_name'); //set your database name
$sql="SELECT method,test_name,test_code FROM vtest_ord ORDER BY
test_ord_id DESC";
echo"<table border='1'><thead><tr><th>Method</th><th>Test Name</th><th>Test
Code</th></tr></thead>";
$result = mysql_query($sql); // execute query
while ($row=$mysql_fetch_assoc($result)) {
echo "<tr><td>";
echo "<td>" . $row['method'] . "</td>";
echo "<td>" . $row['test_name'] . "</td>";
echo "<td>" .
$row['test_code'] . "</td>";
echo "</tr></td>"; }
echo '</table>';
You forgot to call mysql_query method.
Then you could use the returned resource with the mysql_fetch_assoc function in which you have a typo. You're treating it as a variable and not a function.
Try this, You need execute the query using mysql_query, Also, mysql_fetch_assoc not a $mysql_fetch_assoc function
$query ="SELECT method,test_name,test_code FROM vtest_ord ORDER BY test_ord_id DESC";
$result = mysql_query($query) or die(mysql_error());
Should be
while ($row=mysql_fetch_assoc($result)) {
instead of
while ($row=$mysql_fetch_assoc($result)) {
Note: Use mysqli_* functions or PDO instead of using mysql_* functions(deprecated)
Here you can find good tutorial for connecting mysql database: http://us2.php.net/manual/en/mysqli.query.php
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
This code is supposed to show the number of rows in the column "id". Why isn’t is working, when I go to the page it shows nothing except my HTML stuff?
<?php
$con = mysql_connect("quollcraft.net", "quollcr1_forum", "password");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("quollcr1_hub", $con);
$result = mysql_query("SELECT id FROM table ORDER BY id DESC LIMIT 1 ");
echo "<table>";
while ($row = mysql_fetch_array($result)) {
echo "<td>";
echo "<center>";
echo '<p>' . $row ['id'] . ' total users<p>';
echo "</td>";
}
echo "</table>";
mysql_close($con);
?>
Your table name you are using are just table. I guess it should be changed to the real table name from which you want your data
table is one of the reserved word(s) in MySQL. You need to wrap them using backticks.
Like this..
$result = mysql_query("SELECT id FROM `table` ORDER BY id DESC LIMIT 1 ");
^ ^ //<---- Like that
This (mysql_*) extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, Prepared Statements of MySQLi or PDO_MySQL extension should be used to ward off SQL Injection attacks !
Others have decent MySQL tips, but what happens when you view the source code? Because the HTML seems to be broken at best. This is the cleaned up version based on what I am seeing.:
echo "<table>";
echo "<tr>";
while ($row = mysql_fetch_array($result)) {
echo "<td>";
echo "<center>";
echo '<p>' . $row ['id'] . ' total users<p>';
echo "</center>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
You were missing the table row tags <tr> & </tr> as well as the closing </center> tag.
Looks like you are trying to retrieve the total count of ID(users) but you missed out the keyword count. You can modify either the query or you can get the count of $result. Hope this helps.
Result is returning a resource id 5 error not sure what for but i am new too this
The main issue is that my if statement is not working and i thought that was due to my result
$query = "select * from logindetails where online='1'";
$result = mysql_query($query);
echo $result;
if (mysql_num_rows($result) == 1) {
while ($row = mysql_fetch_array($result)) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname'];
}
} else {
}
mysql_close();
?>
It's not really an error. The problem is echo $result; - You can't just print that. It doesn't know what you want to print. Also, I suggest using mysqli.
You're not really getting an error. What you're seeing is a numeric resource identifier for an external resource which in this case, is a resource in the database. Probably what you're looking for is mysql_num_rows() which will tell you the number of rows returned. You'll notice by following that link that the mysql* functions are deprecated and it's recommended that you use mysqli or PDO.
The above code outputs resource id 5 because you have given echo in the 3 line,which means your query is valid ,and the code is correct,Try giving echo mysql_num_rows($result)
Instead of echo $result, use echo $result->Row; The $result itself is an object. You want to access the Row attribute of that object.
Your if statement is only going to work if only one user is online, also. If there are more than one users online, then you are going to have more than one row, so your if statement breaks.
Try
foreach ($result as $row) {
echo $row['online'] . $row['username'] . $row['password'] . $row['emailaddress'] . $row['familyname'] . $row['givenname']. "\n";
}
I have this table:(megaoverzicht.php) (I left out the part where it connects to the db)
echo "<table border='1'><tr><th>Formulier Id</th><th>Domeinnaam</th><th>Bedrijfsnaam</th><th>Datum</th><th>Periode</th><th>Subtotaal</th><th>Dealernaam</th><th>Offerte Maken</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['formuliernummer'] . "</td>";
echo "<td>" . $row['domeinnaam'] . "</td>";
echo "<td>" . $row['bedrijfsnaam'] . "</td>";
echo "<td>" . $row['datum'] . "</td>";
echo "<td>" . $row['periode'] . "</td>";
echo "<td> € " . $row['subtotaal'] . "</td>";
echo "<td>" . $row['dealercontactpersoon'] . "</td>";
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id).
This is the code from (offertemaken.php)(I left out the part where it connects to the db)
<?php
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
?>
<form>
<div class="formcontainer" onmousemove="">
<input type="text" name="datum" id="datum" value="<?php echo $data2[datum]?>">
<input type="text" name="formuliernummer" id="formuliernummer" value="<?php echo $data2[formuliernummer]?>">
<input type="text" name="periode" id="periode" value="<?php echo $data2[periode]?>">
<input type="text" name="domeinnaam" id="domeinnaam" value="<?php echo $data2[domeinnaam]?>">
<input type="text" name="bedrijfsnaam" id="bedrijfsnaam" value="<?php echo $data2[bedrijfsnaam]?>">
<input type="text" name="dealercontactpersoon" id="dealercontactpersoon" value="<?php echo $data2[dealercontactpersoon]?>">
</div><!--/.formcontainer-->
</form>
I cant get it to work. I am missing something I think! I make an error in the codes below:
echo "<td><a href='offertemaken.php?id=" . $row->id . "'>Offerte Maken </a></td>";
$id=$_POST['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
I have been looking at a lot of tutorials but cant understand what i am doing wrong. Here a list to show that i am not just asking but actually have been looking for a solution by myself.
http://www.daniweb.com/web-development/php/threads/341921/-php-mysqli-update-database-using-id-syntax-help-requested-
http://www.codeofaninja.com/2012/01/phpmysqli-update-record.html
I have looked at many more but i don’t want to bother all of you with an extreme long list of links. And i am not allowed because my rep is not big enough! Dont downvote me please!
Question
I want to open offertemaken.php when the user clicks on Offerte Maken. It needs to open the form with the data from that row(id)?
Edit 1 Getting closer to the endresult
I found out(thanks to Cuba32) that the link in megaoverzicht.php was doing nothing so i changed the following
<a href='offertemaken.php?id=" . $row->id . "'>
to
<a href='offertemaken.php?id=" . $row['id'] . "'>
Now it is creating these kind of links:
something/formulieren/overzichten/offertemaken.php?id=24
This is a good thing(i think) but the form that opens is blank so offertemaken.php is doing nothing with the id???
Edit 2 (Thanks to Cube32)
Since yesterday the code has changed quite a bit. I belive that megaoverzicht.php is finished it sends the link as described in edit 1. The only problem is know in offertemaken.php. Below i will put in the code.
$con = mysqli_connect($server,$username,$password,$database);
if (!$con){
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,$database);
$id=$_GET['id'];
if($data = mysqli_prepare($con, 'SELECT * FROM cypg8_overzicht WHERE id="?"'))
{
/* bind parameters for markers */
mysqli_stmt_bind_param($data, "s", $id);
/* execute query */
mysqli_stmt_execute($data);
$data2 = mysqli_stmt_fetch($data);
But this code gives me the following error.
Warning: mysqli_stmt_bind_param(): Number of variables doesn't match number of parameters in prepared statement in line 31. Line 31:
mysqli_stmt_bind_param($data, "s", $id);
I dont know how to solve this part. I will offcourse be looking on the internet to try and find a solution but if anyone knows it please post it. Thanks in advance.
Edit 3<= No more error (Thanks to Your Common Sense)
by changing WHERE id="?"' into WHERE id=?' i no longer have the error. But still it is not showing anything in the input fields
Edit 4<= Getting to confused and going back to original code.
Thanks for everyone who got me so far. But I can't see the forest anymore through the trees. I am going back to the original code and try to solve that. So the code is now as follows:
$id=$_GET['id'];
$data = 'SELECT * FROM cypg8_overzicht WHERE id="$id"';
$query = mysqli_query($con,$data) or die("Couldn't execute query. ". mysqli_error());
$data2 = mysqli_fetch_array($query);
error_reporting(E_ALL);
But this gives the following errors inside the input fields:
Notice: Use of undefined constant formuliernummer - assumed 'formuliernummer' in offertemaken.php on line 37
This error goes for all the input fields.
Edit 5
Fixed this by changing <?php echo $data2[formuliernummer]?> to <?php echo $data2['formuliernummer']?> but it is still not showing the information.
Edit 6 THE SOLUTION
I added the answer to the question below. Just look for answer written by HennySmafter.
Thanks to:
Cube32, SITDGNymall, Your Common Sense. Thanks all of you for helping me find the solution.
It took me a while but i found the answer.
megaoverzicht.php
echo "<td><a href='offertemaken.php?id=" . $row['id'] . "'>Offerte Maken </a></td>";
offertemaken.php
// Check whether the value for id is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen id
$result = mysqli_query($con,"SELECT * FROM cypg8_overzicht WHERE id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysqli_error($result) . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysqli_fetch_assoc($result)) {
echo $row['formuliernummer'] . "\n";
echo $row['domeinnaam'] . "\n";
echo $row['bedrijfsnaam'] . "\n";
echo $row['datum'] . "\n";
echo $row['periode'] . "\n";
}
} else {
die("No valid id specified!");
}
It is not showing the values in the input boxes because there are no input boxes into the echo but those can be easily added I imagine.
In reference to the edit 1:
You are referencing the variables by association, but are outputing the mysql as a default array. instead of
$data2 = mysqli_fetch_array($query);
Try this:
$data2 = mysqli_fetch_assoc($query);
Or:
$data2 = mysqli_fetch_array($query, MYSQLI_ASSOC);
Also, do you have error reporting turned on? If so, then if the array contains no data you should be getting warnings of some kind. If not, a good test is:
error_reporting(E_ALL);
This will warn you about any places where a variable is unset or a array is empty. Another good test is to simply echo out your query, which will tell you if there's any errors in the query itself(which can save some time). If you're not going to go the Prepared Statements route(which is highly encouraged), you can simply echo out $data into your script.
I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!
This question already has answers here:
How can I use PDO to fetch a results array in PHP?
(2 answers)
Closed 2 years ago.
I have a php script that selects data via mysql_, however recently I have been reading that PDO is the way to go and that mysql_ is becoming depreciated. Now I am converting that script to PDO.
My question is though, I am not using $_POST to select. I just want to select the entire table with all of its data so I enter this query :
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchall(); // or you can just $result = $query as hakre proposed!
so then like I did with my old depreciated mysql_ version of the script I used the echo to echo a table with the data in it.
echo
"<table border='2'>
<tr>
<th>ID</th>
<th>A Number</th>
<th>First Name</th>
<th>Last Name</th>
<th>Why</th>
<th>Comments</th>
<th>Signintime</th>
</tr>"
;
foreach($result as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" .$row['anum'] . " </td>";
echo "<td>" . $row['first'] . "</td>";
echo "<td>" . $row['last'] . "</td>";
echo "<td>" . $row['why'] . "</td>";
echo "<td>" . $row['comments'] . "</td>";
echo "<td>" . $row['signintime'] . "</td>";
echo "<td> <input type=\"button\" value=\"Start Session\"onClick=\accept.php?id=" . $row['id'] . "&start=true></td>";
}
echo "</tr>";
echo "</table>";
now using this, I can not get a single output to my table.
My question is am I missing something from my select statements? Or am I not fetching any rows? Also I the connection settings set in another script called connect.php that is required by init.php (at the top of all of my pages)
Edit : 1
Edited the code so it now works, also adding a picture to show others how it should look! Hopefully some one can put this to some sort of use!
You are doing too much actually:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
The problematic line is:
$result = $dbh->query($query);
Check with http://php.net/pdo.query, the parameter is a string, actually the SQL string you already use above, not the result value of a PDO::prepare() call.
For your simple query you can just do:
$result = $dbh->query("SELECT * FROM students");
Or if you like to prepare:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query;
The later is some boilerplate if you want to insert variables into the query, that's why you prepare it.
The next problem is with the foreach line:
foreach($result as $row);
You are terminating the loop immediately because of the semicolon ; at the end. Remove that semicolon so that the following angle-bracketed code-block becomes the body of the foreach-loop.
Your code is wrong:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $dbh->query($query);
After executing a prepared statement, you can just call fetchAll() on it:
$query = $dbh->prepare("SELECT * FROM students");
$query->execute();
$result = $query->fetchAll();
The rest of your code will work fine once you remove the semicolon after the foreach.