When I run the below code i get an error message C:\wamp\www\web\polling\includes\resul and Warning: mysqli_query() expects parameter 1 to be mysqli, integer given i
<?php
$pollid = $_POST['foodID'];
$connection = include('connection.php');
$query = "SELECT * FROM polling WHERE foodID='$pollid'";
$q = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($q)) {
$id = $row[0];
$food = $row[1];
$foodRate = $row[2];
$userEmail = $row[3];
echo "<h1>$food</h1>";
echo "<h1>$userEmail</h1>";
}
?>
Try mysqli_affected_rows() and see if $q is getting any data, if not it will never enter the while loop
Besides that it appears there is an issue in your connection, can you display how your connecting in connection.php?
I'm not sure but the two different types of mysql interactions on the same page raises a red flag. Do you have other pages that work with two types of mysql interactions?
EDIT 1: Try this
$connection = mysqli_connect("localhost", "root", "", "test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
This should work for your first script
Is there a reason your using two different types of mysql interaction?
You are missing a symbol in the statement
$query = "SELECT * FROM polling WHERE foodID='$pollid'";
s/b
$query = "SELECT * FROM `polling` WHERE foodID='$pollid'";
Related
In the following code I'm attempting to connect to my database, pull the maximum ID from my table and then generate a random number using the the rand() function. The code successfully connects me to the the database but when I try to call for the maximum ID it won't return a value.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) FROM 'table'";
$rannmr = rand(1, $amount);
// Close the mysql connection
mysqli_close($dbLink);
?>
Any help in resolving this would be appreciated.
When I try to echo the variable, it returns SELECT MAX(id) FROM 'file'.
Firstly, you are using the wrong identifier for FROM 'table' being single quotes.
If table is indeed the table's name, wrap it in backticks, your question shows file.
$amount = "SELECT MAX(id) FROM `table`";
Either way, you cannot use quotes around a table name. It appears you are using file as your table name.
So if table is only an example and it is called file let's just say, you would do:
$amount = "SELECT MAX(id) FROM `file`";
or
$amount = "SELECT MAX(id) FROM file";
Then, you also need to query, using mysqli_query() which you are not doing.
$amount = mysqli_query($dbLink,"SELECT MAX(id) FROM `file`");
Or Object oriented style:
$amount = $dbLink->query("SELECT MAX(id) FROM `file`");
if($amount){
echo "Success!";
}else{
die('Error : ('. $dbLink->errno .') '. $dbLink->error);
}
See example #1 from http://php.net/manual/en/mysqli.query.php
Use or die(mysqli_error($dbLink)) to mysqli_query() which would have signaled the error.
http://php.net/manual/en/mysqli.error.php
Edit:
Try the following. You may need to modify $row[0] and rand(0,$count) as 1 depending on the column number.
$result = $dbLink->query("SELECT MAX(id) FROM mytable")
while ($row=$result->fetch_row()) { $count = $row[0]; }
$random = rand(0,$count);
echo $random;
use this:
$amount = "SELECT MAX(id) FROM table";
You forgot to execute the MySQL-query:
$amount = $dbLink->query("SELECT MAX(id) FROM table")->fetch_assoc();
$rannmr = rand(1, $amount[0]);
You never executed the query, you need more logic
if ($result = mysqli_query($dbLink, "SELECT MAX(id) as amount FROM `table`")) {
printf("Select returned %d rows.\n", mysqli_num_rows($result));
if ($row = mysqli_fetch_assoc($result)) {
$amount = $row['amount'];
$rannmr = rand(1, $amount);
}else{
echo 'no row found';
}
}
mysqli_close($dbLink);
I didn't seem to see the line of code which actually does the query:
Try this: Using the object-oriented mysqli approach
<?php
// Connect to the database
$dbLink = new mysqli('localhost', 'username', 'password', 'database');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error()); }
$amount = "SELECT MAX(id) as max_id FROM 'table'";
// Do the actual query :
$run_query = $dbLink->mysql->query($amount);
// Retrieve the values:
$result = $run_query->fetch_array();
// Do the rand function together with the retrieved value
$rannmr = rand(1, $result['max_id']);
// Now you can echo the variable:
echo $rannmr;
// Close the mysql connection
mysqli_close($dbLink);
?>
Thanks!!
I want to count the rows in the users table with specific name and pwd which should be 1 if existed.
but the result always return null(not 0),no matter whether the user existed or not.
I even change the query simple to "SELECT * FROM users", and it ended with the same result.
And I am pretty sure that the name of the DATABASE and TABLE are true,and the table is not empty!
By the way,why I have to use "#" symbol before "mysqli_query" in order to get rid of error?
thx!
enter code here
<?php
#$mysql_db_hostname = "localhost";
$mysql_db_hostname = "127.0.0.1";
$mysql_db_user = "root";
$mysql_db_password = "";
$mysql_db_database = "smartFSUsers";
$con = mysqli_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password,$mysql_db_database);
if (!$con) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
$name = $_GET["name"];
$password = $_GET["password"];
$query = "SELECT * FROM users WHERE name='$name' AND password='$password'";
$result =#mysqli_query($query,$con);
echo($result);
$row=#mysqli_num_rows($result);
echo"the row num is $row \n";
?>
RTM: http://php.net/mysqli_query
$result =#mysqli_query($query,$con);
You've got your parameters reversed. $con MUST come first:
$result = mysqli_query($con, $query) or die(mysqli_error());
If you had bothered adding error correction to your code, you'd have been told about this. But nope, you opted for # to hide all those error messages.
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'];
}
I need to print data from users table for username that is logged in, for example, need to bring HP, attack, defence, gold... I found many answers here and after this I am sure I am gone ask more questions. Please help...
<?php
session_start()
if(isset($_SESSION['username'])){
echo "Welcome {$_SESSION['username']}";
}
require_once 'config.php';
$conn = mysql_connect($dbhost,$dbuser,$dbpass)
or die('Error connecting to mysql');
mysql_select_db($dbname);
$query = sprintf("SELECT ID FROM users WHERE UPPER(username) = UPPER('%s')",
mysql_real_escape_string($_SESSION['username']));
$result = mysql_query($query);
list($userID) = mysql_fetch_row($result);
echo "Health Points:".$row['HP'];
echo "Attack:";
echo "Defence:";
echo "Gold:";
?>
You have to query for all the information you actually want. So your query should look like this:
SELECT HP,Atk,Def,Gold FROM ...
This will retrieve the named fields from your database and not just the ID.
Also, you never assign your row, it should read
$row = mysql_fetch_row($result);
(But see my comment below).
1 - there is missing ; in the first line
2 - try "SELECT * " instead of "SELECT ID"
3 - $row is not defined , try :
$row = mysql_fetch_assoc($result);
instead of
list($userID) = mysql_fetch_row($result);
check the manual for the difference between mysql_fetch_row and mysql_fetch_assoc
mysql_fetch_assoc
I want to execute a query that i saved in my database like this:
ID | NAME | QUERY
1 | show_names | "SELECT names.first, names.last FROM names;"
2 | show_5_cities | "SELECT cities.city FROM city WHERE id = 4;"
Is this possible ?
I am kinda noob in php so plz explain if it is possible.
If I understand you correctly, you have your queries saved in the database in a table and you want to execute those.
Break the problem down: you have two tasks to do:
Query the database for the query you want to run.
Execute that query.
It's a bit meta, but meh :)
WARNING: the mysql_ functions in PHP are deprecated and can be dangerous in the wrong hands.
<?php
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
die('Could not connect to mysql');
}
if (!mysql_select_db('mysql_dbname', $link)) {
die('Could not select database');
}
$name = "show_5_cities"; // or get the name from somewhere, e.g. $_GET.
$name = mysql_real_escape_string($name); // sanitize, this is important!
$sql = "SELECT `query` FROM `queries` WHERE `name` = '$name'"; // I should be using parameters here...
$result = mysql_query($sql, $link);
if (!$result) {
die("DB Error, could not query the database\n" . mysql_error(););
}
$query2 = mysql_fetch_array($result);
// Improving the code here is an exercise for the reader.
$result = mysql_query($query2[0]);
?>
if you did create a stored procedure/function you can simply use:
mysql_query("Call procedure_name(#params)")
Thats will work. reference here: http://php.net/manual/en/mysqli.quickstart.stored-procedures.php
Querying the table to get the query, then executing that query and looping through the results and outputting the fields
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$RequiredQuery = intval($_REQUEST['RequiredQuery']);
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $sql);
if ($row = mysqli_fetch_assoc($result))
{
$sql = "SELECT `QUERY` FROM QueryTable WHERE ID = $RequiredQuery";
$result = mysqli_query($link, $row['QUERY']);
while ($row2 = mysqli_fetch_assoc($result))
{
foreach($row2 AS $aField=>$aValue)
{
echo "$aField \t $aValue \r\n";
}
}
}
?>
just open the Table and get the individual query in a variable like
$data = mysql_query('SELECT * FROM <the Table that contains your Queries>');
while(($row = mysql_fetch_row($data)) != NULL)
{
$query = $row['Query'];
mysql_query($query); // The Query from the Table will be Executed Individually in a loop
}
if you want to execute a single query from the table, you have to select the query using WHERE Clause.