I have tables in one db, and one is foreign keyed to the other. My problem is that I'm trying to call up information stored in one table based on the user name which links the 2 tables stored in the other. Here is my php, mind you I'm pretty fresh on the databasing and php, so cut some slack. Here is my code:
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
while($row = mysql_fetch_assoc($gal_result,MYSQL_ASSOC))
{
foreach($results['shoot_name'] as $result)
{
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1) {
die("No galleries found for this user.");
}
}
}
You can google "PHP PDO tutorial" and find many resources. Here's one that is very clear and well written: like: https://phpdelusions.net/pdo
Here's a better example:
<?php
$loaduser = $_SESSION['username'];
// use PDO, not the deprecated mysql extension
$dsn = "mysql:host=localhost;dbname=user_register";
$conn = new PDO($dsn, "DB_USER", "DB_PASS");
// set exception errmode, so code dies automatically if there's an error
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// use a parameterized query instead of concatenating variables into SQL
$sql = "SELECT shoot_name FROM images WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->execute([$loaduser]);
// fetch all into an array of results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// check the count of the results with < 1 instead of != 1
// in case it's 2 or more
if ($stmt->rowCount() < 1) {
die("No galleries found for this user.");
}
// loop through results
foreach($results as $row) {
// use dot for string concatenation instead of comma.
echo $row["shoot_name"] . "<br>";
}
$results has to be fetched before tryin to get its contents.
While trying to get its contents you were fetching $row instead of $results
You are using mysql, mysql has been deprecated try using mysqli or PDO in the future.
Try this anyway.
<?php
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
$results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)
while($results = mysql_fetch_assoc($gal_result,MYSQL_ASSOC)){
foreach($results['shoot_name'] as $result) {
echo $result['shoot_name'], '<br>';
if(mysql_num_rows($gal_result) !=1){
die("No galleries found for this user.");
}
}
}
?>
Try rewriting to this untested snippet (in case you want to keep using deprecated code ;))
$loaduser= $_SESSION['username'];
$loaduser_conn= #mysql_connect("DB_NAME","DB_USER","DB_PASS");
mysql_select_db("user_register") or die ("Couldn't find user database.");
$gal_result= mysql_query("SELECT shoot_name FROM images WHERE username='$loaduser'") or die (mysql_error());
if(mysql_num_rows($gal_result)==0){ // returns number of rows so if 0 there are no rows
die("No galleries found for this user.");
}
while ($row = mysql_fetch_array($gal_result)) { // "while" is already your loop. No need for the foreach within.
echo $row['shoot_name'], '<br>';
}
If you want to select from multiple tables with some reference try this query:
$gal_result= mysql_query("SELECT shoot_name FROM images AS a LEFT JOIN your_other_table AS b ON a.username = b.username WHERE a.username='$loaduser'") or die (mysql_error());
Like anyone i would advise you on using more up to date code.
See here for more info: http://php.net/manual/de/function.mysql-query.php
Related
I need to count the number of instances of a word in a column from my database and then get a true or false result depending on if it exceeds 36 instances. I use wordpress and I know that the connecction to the database is correct. And I am using wordpress.
This is what I got this far but its not working:
$selected = mysql_select_db("bringes_phpbb3", $dbConn) or die("Could not select database. The error was ".mysql_error());
mysql_query("SET NAMES utf8");
$SQL_COUNT ="SELECT COUNT(field_name) AS total_number FROM cyklister WHERE grupp LIKE CONCAT ('%','word','%')";
$result = mysql_query($SQL_COUNT);
if ($result >= 36){
$awnser = true;
mysql_free_result($result);
mysql_close($dbConn);
The SQL query is not complete or may be far from what I am looking for. Can someone help me?
After executing mysql_query, you need to call mysql_fetch_array to retrieve the result:
$result = mysql_query($SQL_COUNT);
$row = mysql_fetch_array($result);
$count = $row[0];
if ($count >= 36) {
$awnser = true;
}
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 have a JSON file that brings data in to iOS. I also want it to see if there are more than 2 records.
If there is more than 2 records i want it to delete everything apart from the last 2 records
How do I insert this in to this php file
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if(!$connection)
{
die("Database server connection failed.");
}
else
{
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if(!$dbconnect)
{
die("Unable to connect to the specified database!");
}
else
{
$query = "SELECT * FROM test ORDER BY id DESC LIMIT 1";
$resultset = mysql_query($query, $connection);
$records = array();
//Loop through all our records and add them to our array
while($r = mysql_fetch_assoc($resultset))
{
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
You are using LIMIT 1 which will mean you only get 1 record back. Are you planning on increasing the limit?
You could always use the PHP count() function and the array_slice() function if you need to cull down an array of records returned...
http://php.net/array_slice
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.
I want to display some basic data from a MySQL database. Here's the current code I have, but it doesn't seem to work. Could someone please explain why this doesn't work and offer a solution? Thanks!
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM 'users' ORDER BY 'DATE' DESC LIMIT 8';
echo = "'$result'"
?>
Providing your connection and structure information is correct, the following should work for you:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$result = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$query = mysql_query($result) or die("Query Error");
while($row = mysql_fetch_assoc($query))
{
echo = "'" . $row['user'] . "'";
}
?>
You forgot to query the database!
You need to use mysql_query() to retrieve data from your DB server, then loop through it with a while() loop.
Also, you can't use quotes inside quoted strings - it breaks the string, meaning you'll get a syntax error with the SELECT ... line. You don't actually need to quote database fields in queries, so the following should work fine:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM users ORDER BY DATE DESC LIMIT 8';
$result = mysql_query($query); // Query the database.
// Loop through each returned row
while($row = mysql_fetch_assoc($result))
{
print_r($row); // Prints the current row
}
?>
To show any errors that PHP reports, put these two lines at the top of your script.
error_reporting(E_ALL);
ini_set('display_errors', '1');
They will output any errors you get, making problems much easier to solve.
After the selecting the database need
$stmt = mysql_query("SELECT * FROM users ORDER BY DATE DESC LIMIT 8");
while ($result = mysql_fetch_array($stmt, MYSQL_NUM))
{
var_dump($result);
}
mysql_free_result($stmt);
You should query your string and then echo the result, like this for example:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("cede") or die("Couldn't find database");
$query = 'SELECT * FROM `users` ORDER BY `DATE` DESC LIMIT 8';
$result = mysql_query($query);
echo = "'$result'"; // This may need a foreach loop
?>
You should escape the ' in your string, because you use them to open and close your string too. The syntax highlighter actually tells you that you are wrong ('users' and 'DATE' are black instead of maroon). :)
Please see the PHP.net documentation about strings:
After that, you'll need to further process $result. It is just a resource pointer and cannot be echoed that way. But that's a second step. :)