getting fatal error message - php

I'm getting the below message on my second page and nothing works...
Fatal error: Call to a member function fetch_assoc() on a non-object in C:\xampp\htdocs\send.php on line 6
here is the first page where I display the Email address and it works nice but when I click on the email and go to info.php I get that error.. What is wrong?
<?php
$mydb = new mysqli('localhost', 'root', '', 'database');
$sql = "SELECT * FROM test ";
$result = $mydb->query($sql);
while( $row = $result->fetch_assoc() ){
echo '<td>'.$row['Email'].' </td>';
echo "<br/>";
}
$mydb->close ();
?>
here is info.php..Just bear in mind that I'm trying to display row Age and Name of single user which I have in a same table in a database ..
<?php
$mydb = new mysqli('localhost', 'root', '', 'database');
$sql = "SELECT * FROM User WHERE id = " . $_GET['email'];
$result = $mydb->query($sql);
while( $row = $result->fetch_assoc() ){
echo $row['Age'] . " " . $row['Name'] ;
echo "<br/>";
}
$mydb->close ();
?>

It means your query did not run correctly. You should put a check:
if (!$result) {
echo $mydb->error;
}
die();
Prepared Statements
You should use them since you're taking user input. Prepared statements provide a good level of cleansing input, so that users can't mess with your database.
It also looks like you have a column for email, but are trying to select a user based on:
id = email.
It's common practice to make id an INT, and email would probably be VARCHAR, so this comparison doesn't make sense (if your table schema is following common practice)

The query is failing because you aren't putting quotes around the email address.
$sql = "SELECT * FROM User WHERE id = '" . $_GET['email'] . "'";

Related

Display Bids from database in order

Ive been trying to display a "bid" from the database to no success.
here is my error
Fatal error: Function name must be a string in /home/rslistc1/public_html/get-bids.php on line 7
here is my code
<?php
include('session.php');
?>
<?php
require_once('mysql_connect.php');
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
$result3 = mysql_query($query3) OR die($mysql_error());
$num = mysql_num_rows($result3);
while ($row = mysql_fetch_array($result3, MYSQL_ASSOC)) { ?>
<?php echo''.$row['bid'].'';
}
?>
Any idea
Before we address the line 7 issue, lets check other errors. In order to request a query to a MYSQL database, we need to create a connection:
$con = mysqli_connect("ip_address","user","password","database_name");
Once we have that connection, let us check if we can actually connect to the database:
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
Appreciate that mysqli_error() function uses the connection. Now the query string:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '$login_session'";
You are sending a query to look for a username called "$login_session" and it would most likely not find any match. To add strings from variables will be as follow:
$query3 = "SELECT id, username, bid FROM bids WHERE username = '" . $login_session . "'";
Now, for the error in line 7
result3 = mysql_query($con, $query3) OR die($mysql_error($con));
As you can see, both mysql function use the connection to check for errors. Try it and let me know if everything works fine.
Edit:
Terribly sorry my friend, I just forgot to put a little letter "i" on the line, also, I would like to show you my way to deal with the query result. First, the line as it should be:
$result3 = mysqli_query($con, $query3);
Notice the i after mysql. Now let us check whether we got some rows or not:
if (!$result3) {
die('Could not retrieve data: ' . mysqli_error($con));
} else {
while ($row = mysqli_fetch_array($result3)) {
//Show your results
}
}

PHP/MySQL where clause returning an empty value

I have a small problem using the Where clause for PHP/MySQL in the code shown below:
<?php
$con=mysqli_connect("host","username","password","database");
//Note that I have replaced my parametres just for this question
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Request Session ID
$id = $_SESSION['uid'];
echo "Session ID = ' . $id;
echo "<br>";
//Request Username
echo "Username = " . mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");
?>
The output of this is (after logging in on my separate login page):
Session ID = 4
Username =
So it is evident that there is an issue with the where clause.
There is no issue with the connection parametres as far as I am aware.
When I run the MySQL command in PHPmyadmin I get the expected result of 'Admin'.
My inputs are correctly named.
I have no idea what is causing this and I can't find any similar problems on the forum. Any help would be appreciated. Thanks.
UPDATE
I have adapted the below answers to make this code:
<?php
// Only run this script if the sendRequest is from my flash application
if ($_POST['sendRequest'] == "parse") {
//conection:
$con=mysqli_connect("mysqlXX.000webhost.com","a4935911_***","***","a4935911_***");
$id = $_SESSION['uid'];
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = $id"));
$uname = $getuname ['username'];
// Print 1 var to flash
print "var1=The username of this user is $uname.";
}
?>
Which is triggered by my flash application. This works fine if I do not use session ID variable and just use e.g. 4 as my id value but I need to use the session ID for this. Any ideas what is up with this?
You shouldn't surround table names with ordinary single quotes ('); use backticks instead (or, if you don't use reserved words, none). So:
SELECT username FROM `users` WHERE id = 4
or
SELECT username FROM users WHERE id = 4
Moreover, mysqli_query doesn't return the result in the field, but a mysqli_result object. You'll have to use a fetch command to get the result(s), e.g.
$result = mysqli_query($con,"SELECT username FROM 'users' WHERE id = 4");
$row = mysqli_fetch_assoc($result);
echo 'Username = ' . $row['username'];
You should use the following code:-
//conection:
$con=mysqli_connect("host","username","password","database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$getuname = mysqli_fetch_assoc(mysqli_query($con, "SELECT username FROM users WHERE id = 4"));
$username = $getuname ['username'];
//Request Username
echo "Username = " .$username ;

Str_Replace with query results

I have a MySql DB and in the Table 'Klant' I have the column names:
ID
Naam
Email
Soort
Status
I get the column names with this query:
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
And I am selecting the data from the Table with this simple query:
$strSQL1 = "SELECT * FROM NAW.Klant";
What I want to do is search a text and with str_replace I want to replace the column_names with the data from the DB. For example:
If I type in Hello Naam, your email adress is Email I would want it to display Hello Robert your email adress is robert#gmail.com. And I will put that in a loop to do it for every row. I am currently using this:
$ID = $row['Klant_ID'];
$Naam = $row['Naam'];
$Email = $row['Email'];
$Soort = $row['Soort'];
$Naam = $row['Status'];
$vaaw = array("[ID]","[Naam]", "[Email]", "[Soort]", "[Status]");
$vervang = array("$ID","$Naam", "$Email", "$Soort", "$Status");
echo str_replace($vaaw, $vervang, $message);
The reason I do not want to use this anymore is because if I ever need to change/add/delete a column the code would still work. (I know it is a bad idea to change columns but you never know.) And also this code will work with other Tables/DB's to.
I have tried loads of things to get this to work but I just haven't got a clue how to do this and it has been bugging me for almost 2 days now. If someone knows a function or a way to do this it would be very helpful!
Try this:
<?php
$strSQL = "select column_name from information_schema.columns where table_name='Klant'";
$con=mysqli_connect('host', 'username', 'password', 'db');
if(!$con){
//error
}
$result=mysqli_query($con,$strSQL);
if(!$result){
//error
}
$table_columns=array();
//$row=mysqli_fetch_assoc($result);
while($row=mysqli_fetch_assoc($result))
{
$table_columns[]=$row['column_name'];
}
$query="select * from NAW.Klant "; //limit 10";
$result=mysqli_query($con,$query);
if(!$result){
//error
}
$greeting_text="";
while($row=mysqli_fetch_assoc($result)){
$greeting_text.= (isset($row['naam']))? "Hello {$row['naam']}":""; // because you want the 'hello'
for($i=1;$i< count($table_columns);$i++){
$greeting_text.=" Your ".$table_columns[$i]." is ".$row[$table_columns[$i]].", ";
}
$greeting_text.="\n";
}
echo $greeting_text; //test your result
If you have a predefined string template (to be replaced by column names or their values), you need to change that code when there is any change in the table columns. I simply choose to dynamically generate the string depending on the availability of columns. But if you need to use a predefined string, it is not difficult to do so.
I solved it using the script that HamZa linked in the comments. Since he is not posting it as an answer I will do it myself because I think it could help others.
The code that solved the problem is this:
$connection = mysql_connect('localhost', 'root', 'pw') or die('couldn\'t connect to the database.<br>'. mysql_error());
mysql_select_db("NAW");
$strSQL1 = "SELECT * FROM Klant";
$result = mysql_query($strSQL1, $connection) or die('Something went wrong with the query.<br>'. mysql_error());
while($row = mysql_fetch_assoc($result)){
$text = $_POST['naam'];
foreach($row as $k => $v){
$text = str_replace('['.$k.']', $v, $text);
}
echo $text;
echo "<br>";
}

Using a variable in the WHERE Clause

I am a newbie in MySQL and PHP. I have a HTML form where I would like to pass 1 variable from to my PHP code and then run a query on my database for the record that holds that variable under the column 'Serial'. I can run it fine when I hard code the 'serial' that I want to look up but when I try with the variable I get an error.
Any help would greatly be appreciated! Or a better way to do this.
Here is my error: Unknown column 'amg002' in 'where clause'
Here is my code;
$serial= $_POST['Serial'];
echo $serial;
//Connect To Database
$link = mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
echo "Connected to MySQL<br />";
//Select the database - 'SiteInfo'
// Collects data from "SiteInfo" table
//****This is where I am running into the error***
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial;
// This works!!!
//$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ="amg002";';
$data = mysql_query($sql)
or die(mysql_error());
// puts the "SiteInfo" info into the $info array
$info = mysql_fetch_array( $data );
//Print out the contents of the entry
echo "Site Name: ".$info['SiteName'] . "<br /";
Print "Serial Number: ".$info['Serial'] . "<br />";
Print "Location: ".$info['Location'] . "<br />";
// Close the database connection
mysql_close($link);
echo "Connection Closed. <br />";
I agree its a quote issue, but here is how my code would look.
$sql = 'SELECT * FROM SiteInfo WHERE Serial = "' . $serial . '"';
or
$sql = "SELECT * FROM 'SiteInfo; WHERE 'Serial' = \"$serial\"";
Looks like a quote issue:
$sql = 'SELECT * FROM `SiteInfo` WHERE `Serial` ='.$serial.';
should be
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` ='".$serial."'";
It means your variable:
$_POST['Serial']
is coming empty. You need to run your code if it isn't empty by checking it via isset like this:
if (isset( $_POST['Serial'])) {
$serial= $_POST['Serial'];
// your rest of the code
}
Also if Serial is string and not a number, you need to put it in quotes, use below query:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
You can also check out what does your query come up like:
$sql = "SELECT * FROM `SiteInfo` WHERE `Serial` = '$serial'";
echo $sql;
exit;

Check if value is in mysql's table's column

How can I check if value is in mysql's table's column?
Right now I'm creating a login system. After the user registers my php file posts the value and makes it into a variable. I was wondering what code i can use to compare my value to those values in the table and to check whether or not there is a value identical to the value entered.
I tried this code.
$query = "SELECT * FROM users WHERE username ='$username';";
$res = mysql_num_rows(mysql_query($query));
and then if ($res >= 0);
but then i get this error,
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/synameg1/public_html/giveaway/appfiles/register.php on line 23
so i was wondering if there is either a way to fix this error or do what i want to do in another method.
Thanks!
$sql = "SELECT * FROM users WHERE username = '" . mysql_real_escape_string($username) . "'";
$result = mysql_query($sql) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
Dan: I used your approach with 'zero' result.
<?php
//////////////////////////////////////////////////////////////////////
global $current_user;
get_currentuserinfo();
$user_nam = $current_user->user_login;
$db_host = 'localhost';
$db_user = 'Private'; ////the user name
$db_pwd = 'Private'; /////the pasword
$database = 'Datapase name';/////////
$table = 'Table Name'; ///table name
$sql = "SELECT * FROM $table WHERE 'Submitted Login' = '" . mysql_real_escape_string($user_nam) . "'";
$result = mysql_query($sql) or die("Error occurred in [$sql]: " . mysql_error());
$count = mysql_num_rows($result);
echo $user_nam . "<br />";
echo "count is $count";
////////////////////////////////////////////////////////////////////
?>
Private fields have comments.
It works, I can see $user_nam but the count is zero.
Here is a datebase peek so you can see the values.
http://you-get-real.com/images/database-peek.png
Thanks

Categories