I am trying to query my database using php, to then display the results of the query. For this example, I only want the number of elements in my MySQL database.
My code is:
<?php
print("This is just a test");
print("This is another test");
// Create connection
$con=mysqli_connect("mysql.netsons.com","****","****","****");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
print("A third test");
$result = mysqli_query($con, "SELECT COUNT(*) FROM MyGames");
echo $result;
echo mysqli_fetch_array($result);
print("A forth test");
mysqli_close($con);
?>
This is the result:
This is just a testThis is another testA third test
What am I doing wrong?
mysql_fetch_array fetches ... an array.
$row = mysqli_fetch_array($result);
echo $row["COUNT(*)"];
I think it would be better to alias that column too:
SELECT COUNT(*) AS count FROM MyGames
...
echo $row['count'];
I would recomend using a diferent method of querying that is much safer(As far as I know there is no SQL Injection to worry about) and it saves a lot of time and space.
First you need to create an mysqli object
$stateConnect = new mysqli("localhost", "root", "PASS", "DBTable");
This does the same thing as mysqli_connect and mysqli_select_db
Then you want to define your SQL query
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=?";
Next you want to create a variable called a statement with your SQL "attached to it"
$statement = $stateConnect->prepare($sql);
Notice how in my SQL I didn't directly put the value required for userEmail, instead I put an '?'. This acts as a variable that we will later define(However it will always be a '?'
To define this variable we need to use.
$statement->bind_param('s', $SESSION['email']);
This binds $SESSION['email'] to the first qustion mark, the s is saying that the first question mark will be a string. Lets say we had to varribles:
$sql = "SELECT `userVotes` FROM `users` WHERE `userEmail`=? AND `userName`=?";
We would then use:
$statement->bind_param('ss', $SESSION['email'], "USERNAME");
Each s replresents a question mark and each value after that represents a question mark.
Now we have to execute our query with.
$statement->execute();
If we are expecting a result to be returned then we have to use
$statement->bind_result($userVotesText);
To bind the results to a variable, If I was expecting to columns of results I would need to put a second variable in.
Now to set those varribles we need to use
if($statement->fetch()){
$userVotesResult = userVotesText;
}
This method is much better than other for querying databases and is called Prepared Statement
Related
I've tried to use the solutions presented in this question,
to no avail, so I used this:
$stat = "SELECT MAX(employee_id) FROM employees";
$querysult = intval($connection, $stat);
Where employee_id is an int(3) in the database table.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight. But my question is about what I did immediately after, which was
echo "Id: " . $querysult;
and which output nothing but
Id:
and no number. I've also tried casting the number to a string, and concatenating it to an empty string before the echo statement.
For some reason, the above code actually gets the values from the database, despite there not being a mysqli_query() in sight
This of course is quite impossible, unless you are getting something from a previously executed query that uses the same variable names.
I think your main problem is that accessing the value of the query coded using just SELECT MAX(employee_id) will return a column with the name MAX(employee_id) and that is not a valid PHP variable name. So what you have to do is give that column another name that is a valid PHP variables name using this syntax SELECT MAX(employee_id) as max_empid which renames the column to max_empid
I am assuming nothing so I will also include a connection to the database in my answer. You will need to replace the my_user, my_password and my_db values, or ignore the connection if you have already dont that somewhere else. I have also used the Object Oriented approach to MYSQLI, if you are using the proceedural calls, you may have to amend the code accordingly
// connect to your database
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
// build query and use an alias for the `MAX(employee_id)`
// so you can easily use its name in the result set
$sql = "SELECT MAX(employee_id) as max_empid FROM employees";
// Now we must execute this query
$result = $mysqli->query($sql);
// Now we must chech that the query worked
if ( $result === FALSE ) {
echo sprintf( 'Query Failed: %s<br>%s', $sql, $mysqli->error);
exit;
}
// now we must read one of the rows from the result set
// produced by the ->query() command.
// In this case there of course there is only one result row
$row = $result->fetch_object();
echo 'Id: ' . $row->max_empid;
It may be because you are trying to convert a connection to an int value.
Try this
$connection = new mysqli();
$querysult =mysqli_query( $stat);
printf("Select returned %d.\n", $querysult->num_rows);
All I am trying to do is display the price of an item from an mysql database in an <h1> tag. Nothing fancy or difficult. I have a page that has 60 item on it, and I need to update prices on our database 2 to 3 times a year. This would keep this page consistent with the database.
I have establish a standard mysql connect. I have defined a variable from a select statement. Now I just need to know how to display the info. when I run this php, I get an error "Notice: Undefined variable: products in /Applications/MAMP/htdocs/staging/dynamic_mixers.php on line 123"
Below is my code.
$products = "SELECT Base_Price FROM products Where record_number=1072;
echo "<h1>'.$products['Base_Price'].</h1>
In php, you write the query:
$products = "SELECT Base_Price FROM products Where record_number=1072"; //don't forget end quote
You make a connection to the database like this:
$connection = new mysqli("localhost", "user", "password", "database");
Then you send the query to be processed using the connection, like this:
$results = mysqli_query($connection, $products);
Then you need to loop through the results (even if there is only one)
while ($row = mysqli_fetch_assoc($result)) {
}
In that loop you can access $row['Base_Price']
while ($row = mysqli_fetch_assoc($result)) {
echo $row['Base_Price']
}
Read more about it here: PHP and MySQL
I prefer to use PHP data Objects over mysqli. Better performance and less chance of being susceptible to injection attacks.
// setup the query
$dbh = new PDO
(
'mysql:host=localhost;dbname=myDatabase',
$username,
$password,
array
(
PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC
)
);
$query = $dbh->Prepare('SELECT Base_Price FROM products Where record_number=? LIMIT 1');
// execute for one item
$query->execute(array(1072));
$singlePrice = $query->fetch();
// execute for the next item
$query->execute(array(1073));
$singlePrice = $query->fetch();
// execute for the third item, etc
$query->execute(array(1074));
$singlePrice = $query->fetch();
You can throw all of the executes in a for loop and get maximum performance since PDO is using a prepared statement.
This yields proper results, but I would like to have the resulting row in an array, instead of binding individual variables to each field, so I can access fields like $row[0] and/or $row["name"].
$idToSearch = 2;
$conn = new mysqli("localhost", "username", "password", "db_people");
$statement = $conn->prepare("SELECT name, age from People where id = ?");
$statement->bind_param("i", $idToSearch);
$statement->execute();
$statement->bind_result($name, $age);
if($statement->fetch()) {
echo "The name is $name and the age is $age. ";
} else {
echo "No person found with that id.";
}
Saw an example about fetch_assoc(), but it used a mysqli_result class which I don't know hot to use and unprepared statements which I'd rather not use.
EDIT: To clarify, I'm fine with a solution whether it uses bind_result or not.
In order to use fetch_assoc you would need to use get_results which would force you to not use the bind which it seems you don't want to do. So I believe what you want to do is explained pretty well by user uramihsayibok in the php docs for the bind_result function, specifically here: http://php.net/manual/en/mysqli-stmt.bind-result.php#92505. They explain how to work around that in order get the results into an array.
This is the code I'm using:
<?php
// Set the MySQL Configuration
$db_host = "";
$db_user = "";
$db_password = "";
$db_name = "";
$db_table = "";
// Start Connection
$db_connect = mysql_connect ($db_host, $db_user, $db_password);
// Select Database
$db_select = mysql_select_db ($db_name, $db_connect);
// Update Values in Database
$query = "UPDATE $db_table SET
age = age + 1,
land = '".$_POST['data3']."'
WHERE name = '".$_POST['data1']."'
";
// Execution MySQL query
$result = mysql_query($query) or die(mysql_error($db_connect));
//Close MySQL connection
mysql_close($db_connect);
//HTTP Response
echo " your age: age";
?>
I want to echo the value of the $age variable, but instead I always get the word "age." For example, the code should echo your age: 5 but instead it outputs your age: age
First, you'll need to run a SELECT query to retrieve the updated value of age. The query should look something like this:
"SELECT age FROM db_table_name WHERE name = ?"
Once you've obtained the result of that query, with say PDO::fetch (see my note below about PDO) and set it to the variable $age, you can output it with an echo statement:
echo "Your age: $age";
Also, please don't use mysql_* functions for new code. They are no longer maintained and the community has begun the deprecation process (see the red box). Instead, you should learn about prepared statements and use either PDO or MySQLi. If you can't decide which, this article will help you. If you care to learn, this is a good PDO tutorial.
The reason I'm not giving you the exact code for this is because it shouldn't be done with the mysql_* functions at all. Creating an SQL query with data directly from $_POST like this is extremely dangerous code to use and an incredibly bad idea all around. Never do this. You open yourself up to numerous SQL injection attacks. Even using mysql_real_escape_string is not enough. You should be using prepared statements.
UPDATE: Here is a simple example that's close to what you're asking, but using PDO and prepared statements. This is by no means a comprehensive example, since there are several ways to alter it that will still work (e.g. prepared statements allow you to execute multiple statements on the server in one statement), and I don't have a working server at the moment to test to make sure it's exactly what you need, but I hope it gets the point of across.
<?php
// Create the database connection
$db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password');
// Set PDO/MySQL to use real prepared statements instead of emulating them
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
// The UPDATE query we're going to use
$update_query = "UPDATE `db_table_name` SET age = age + 1, land = :land WHERE name = :name";
// Prepare the query
$stmt = $db->prepare($update_query);
// Bind variables to the named parameters in the query with their values from $_POST
$land = $_POST['data3'];
$name = $_POST['data1']
$stmt->bindParam(':land', $land);
$stmt->bindParam(':name', $name);
// Execute the statement on the server
$stmt->execute();
// The SELECT query we're going to use
$select_query = "SELECT age FROM `db_table_name` WHERE name = :name";
// Again, prepare the query
$stmt_select = $db->prepare($select_query);
// Bind the paramters (in this case only one) to the new statement
// $name is already set from before, so there is no need to set it again
$stmt_select->bindParam(":name", $name);
$stmt_select->execute();
/*
* With no arguments, PDO::fetchColumn() returns the first column
* in the current row of the result set. Otherwise, fetchColumn()
* takes a 0-indexed number of the column you wish to retrieve
* from the row.
*/
$age = $stmt_select->fetchColumn();
echo("Your age: $age");
?>
All of this information came directly from the PHP documentation on prepared statements and PDO::fetchColumn().
What's the correct way to code the following
SELECT * FROM table WHERE value = $row['item']
$row['item'] echos correctly, but does not seem to work in the mysql query. Been having this problem for a few days. I've tried .$row['item']. and a few other variations but I must be doing something wrong.
The better more appropriate approach is to use mysqli and prepared statements ie:
$stmt = $mysqli->prepare("SELECT * FROM table WHERE value =?");
$stmt->bind_param("s",$row['item']); // I am assuming row['item'] is a string
$stmt->execute();
If you can't use mysqli or absolutely refuse to you can use this:
$query = "SELECT * FROM table WHERE value = '".mysql_real_escape_string($row['item'])."'";
The answer sort of depends on what is held within the $row['item'] variable. If it's a numeric value, then the query above should be fine. Since it's not working, I assume that the value of that variable is actually a string. In that case, you need to surround the value in quotes so that the database can correctly identify it as a string value (otherwise, it would just be gibberish "commands" that the database can't identify, causing the query to fail).
Regardless of the above, you shouldn't be directly inserting variables into a query under pretty much any circumstances. The reason is that it opens you up to SQL injection if you're not extremely careful. For example, if your $row['item'] variable was wrapped in single quotes in the query, but contained a single quote in its value, then the database would interpret the quote within the variable as the ending quote for the entire parameter, and it would screw up the query. Worse still, a hacker could take advantage of this to end your query entirely, then add a second query of his own making onto it (or they could introduce a UNION query on the end of the original, etc.). At the very least, you should be running something like mysql_real_escape_string() on the variable before using it:
$sql = "SELECT * FROM table WHERE value = " .
mysql_real_escape_string($row['item']);
The best way to get around this and secure your queries is to use prepared statements. These are queries that have placeholders in them instead of concatenated variables. You prepare the query with these placeholders, then you issue additional commands to the database to tell it what values to place in those placeholders. The database then takes care of the tricky issue of sanitizing these variables so that they don't cause any damage. You can use PDO for this:
try {
$dbh = new PDO(DB_DSN,
DB_USER,
DB_PASS,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
exit();
}
// create query with a named placeholder
$sql = "SELECT * FROM table WHERE value = :value";
try {
$stmt = $dbh->prepare($sql);
// tell PDO to substitute the value in $row['item']
// for the named parameter specified above.
$stmt->bindValue(":value", $row['item']);
// execute the query and load the results into an array
$stmt->execute();
$records = $stmt->fetchAll();
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
exit();
}
foreach ($records as $record) {
// use db records
}
The way I usually recommend doing it is something like this:
$sql = sprintf("SELECT * FROM table WHERE value = '%s'",
mysql_real_escape_string($row['item']));
$item = mysql_real_escape_string($row['item']);
$mysqlQuery = "SELECT * FROM table WHERE value = '" . $item . "'";
you are missing single quotes
SELECT * FROM table WHERE value = '{$row['item']}'
PHP example