EDIT
I connected to my database and I want to verify if I can select my table. They do exist but I always get "Unable to select (one of) the Databases"
if ($DBConnect === false) { //We verify if we are connected to the Database
echo "<p> Connection failed </p>\n";
} else {
//We want to check if there is the two table in the database
$sqlPat = "SELECT * FROM `tbl_patient`";
$sqlUser = "SELECT * FROM `tbl_user`";
$ResultPat = mysqli_query($DBConnect, $sqlPat);
$ResultUser = mysqli_query($DBConnect, $sqlUser);
if (empty($ResultPat) || empty($ResultUser)) {
echo "<p> Unable to select (one of) the Databases</p>";
} else {
$sqlTruncP = "TRUNCATE TABLE `tbl_patient`";
$sqlTruncU = "TRUNCATE TABLE `tbl_user`";
$QResultTP = mysqli_query($DBConnect, $sqlTruncP);
$QResultTU = mysqli_query($DBConnect, $sqlTruncU);
if ($QResultTP) {
echo "<p> Well done my mate ".$sqlTruncP. " done ". $DBConnect->info."</p>";
if ($QResultTU) {
echo "<p> Well done my mate ".$sqlTruncU. " done ". $DBConnect->info."</p>";
}
} else {
echo "<p> No Way Hose - Unable to perform SQL Truncate Table </p>";
}
}
I get 'No Way Hose - Unable to perform SQL Truncate Table' each time
$ResultPat and $ResultUser will return an array not string therefore you have to check with the method given below the array is empty or not.
if (empty($ResultPat) || empty($ResultUser)){
echo "<p> Unable to select (one of) the Databases</p>";
}
you can also check the values in the array but just using
echo "<pre>"print_r($ResultUser);die;
the above code will print your array elements and die will stop the code after your array will be printed on the screen.
Second Question Answer: -
if ($QResultTP)
{ echo " Well done my mate ";
echo " Well done my mate ";
}else
{
echo "<p> No Way Hose - Unable to perform SQL Truncate Table </p>";
}
explaination: -
In your 1st question query will return you an array it may be empty or can have data. empty used to check null,'',0, values in the variable.
they truncate query will not return you any data. it will just truncate the tables.
Related
I have a variable of the logged in user ($steamid) that I need to use to select and echo specific fields from the database. I am using the following code, but it is working incorrectly. All database info is correct, the tables, columns, and variables are not misspelled. Not sure what I'm doing wrong.
<?php
$con=mysqli_connect("private","private","private","private");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "SELECT `bananas` FROM `es_player` WHERE `steamid` = '$steamID'";
if ($result=mysqli_query($con,$sql))
{
// Get field information for all fields
while ($fieldinfo=mysqli_fetch_field($result))
{
printf("bananas: %n",$fieldinfo->bananas);
}
// Free result set
mysqli_free_result($result);
}
mysqli_close($con);
?>
No errors are shown, it simply returns "bananas:" with nothing after it. I feel like I didn't to it correctly, does anyone know what I might've done wrong? Here is a screenshot of my database table so you know what it looks like http://puu.sh/gCY3d/983b738458.png.
Try this:
$query = Mysqli_Query($con, "SELECT * FROM `es_player` WHERE `steamid`='$steamID'") or die(mysql_error());
if( ! mysqli_num_rows($query) )
{
echo 'No results found.';
}
else
{
$bananas_array = mysqli_fetch_assoc($query);
$bananas = $bananas_array['bananas'];
echo 'Number of bananas: '. $bananas;
}
If this doesn't work, there is a problem with STEAM_ID format. You could try triming the IDs to be JUST a number, and add the STEAM_x:x: to it later.
I'm having a problem with some specific PHP code that I've been working on for a few days. It's meant to be a reporting code where I can input a day and a month and it will list the total sales of that particular day.
But, I can't seem to make the last statement whereby, if there are no values(there are no data) in the query, it will display 'No Sales on this particular day'. Here's the code I've been working on. But the last echo statement is not executing. Any ideas?
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
$day=#$_POST['day'];
$month=#$_POST['month'];
echo "<center><h2>Sales report on " .$day. "." .$month. ".2013</h2></center>";
echo "<center><table style='border:2px solid black;' align=center width=600>";
echo "<tr><th colspan=12><center><h2>Sales Report</h2><hr size='2' color='black' /></center></th></tr>";
echo " <th width=400> Amount Collected</th>";
?>
<br>
<?php
$x = 1; //counter
//open a connection to a MySQL server using function mysql_connect
//returns a MySQL link identifier on success, or FALSE on failure.
$conn= mysql_connect("localhost","root","");
if (!$conn)
die ("Connection error: ".mysql_error());
else {
//select a MySQL database
//returns TRUE on success or FALSE on failurue.
$db=mysql_select_db("cqfos");
if(!$db)
die ("DB not found: ".mysql_error());
else {
//put query in a variable $query
$query= "select ROUND(sum(orderdetails.tprice),2)
from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '$day' AND MONTH(orders.date) = '$month'";
$result=mysql_query($query);
if(!$result)
die ("Invalid query: ".mysql_error());
//if record exists
else {
//fetch a result row as both associative array and numeric array
if(mysql_num_rows($result)== 1){
while ($row=mysql_fetch_array($result,MYSQL_BOTH)){
echo "<tr>";
echo "<td align='center'>RM ".$row[0]."</td></tr>";
$x++; //increase the counter
}
}
else {
echo "<tr><th colspan=12>No sales made.</td></tr>";}
}
}
}
echo"</table></center>";
?>
Several problems here
your HTML table syntax is incorrect, and your using an old sql library - and it dose not look like your SQL syntax is right... try this code (not tested as I don't have your data)
<?php
session_start();
if ((isset($_SESSION["admin"])) ){
echo '<div style="margin:auto; textalign:center;">';
echo "<h2>Sales report on " .$_POST['day']. "." .$_POST['month']. ".2013</h2>";
echo "<h2>Sales Report</h2>"
echo "<table style='border:2px solid black;' align=center width=600>";
echo "<tr><th width=400> Amount Collected</th></tr>";
?>
<br>
<?php
$conn = new mysqli("localhost","root","","cqfos");///use mysqli, not mysql : mysql is depricated
if ($conn->mysqli)
exit ("Connection error: ".$conn->errno ." : " $conn->error);
else {
//put query in a variable $query
$eDay = $conn->mysql_real_escape_string($_POST['day']);//escape these to protect the database
$eMonth = $conn->mysql_real_escape_string($_POST['month']);;//escape these to protect the database
//your column name is probably not a rounded value, replaced it with * (return all columns)
$query= "select * from orders JOIN orderdetails ON orders.orderID = orderdetails.orderID WHERE DAY(orders.date) = '"
.$eDay."' AND MONTH(orders.date) = '".$eMonth."'";
$result=$con->query($query);
if($conn->errno)
exit ("Invalid query: ".$conn->errno ." : " $conn->error);
//if record exists
else {
$numericArray = $result->fetch_array(MYSQLI_NUM); //fetch a result row as numeric array
$associativeArray = $result->fetch_array(MYSQLI_ASSOC); //fetch as an associtive array this is not used, just an example
$bothArray = $result->fetch_array(MYSQL_BOTH); //both associtive and numeric this is not used, just an example
}
if(!empty($numericArray))
{
foreach ($numericArray as $value) {
echo "<tr><td>RM ".$value[0]."</td><tr>";//is there more then 1 col? if not you should consider an html list
}
} else {
echo "<tr><td>No sales made</td><tr>";
}
echo"</table></center>";
}
?>
Your SQL (likely) returns more than only one row, so change the line I mentioned before to this:
if(mysql_num_rows($result)>0){
Just letting you know your code is vulnerable to SQLi because you have not sanitized $day and $month. Also please consider using PDO.
If you haven't already - Try running the SQL statement into PHPMyAdmin and see where it outputs the error (if there is one), else it will output the data.*
*Manually inputting the day/month substituting for the variables.
Hi I am trying to fetch data from a particular coloumn from all rows.
Eg Situation:
DB Data: id, fbid, name
$sql = 'SELECT id FROM table WHERE table.fbid IN (1234,5678,4321)';
$sql_run = mysql_query($sql);
$sql_fetch = mysql_fetch_assoc($sql_run);
print_r($sql_fetch);
This returns the data when I test it using Sequel PRO or PHPmyAdmin.
But when I print the array it only displays one value.
Can you help me with a solution or tell me where I'm going wrong?
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result))
{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>
Before using a function, or - at least - when it does not what you expect - it's always a good idea to read the function description in the manual page.
PHP provides extremely easy access to its manual pages. All you need to type in the address bar is php.net/function name. It takes less time than typing whole question on Stack Overflow, yet you will get exactly the same answer. Think of efficiency.
You need to loop through each row
$sql_run = mysql_query($sql) or die(mysql_error());
while ($sql_fetch = mysql_fetch_assoc($sql_run)) {
print_r($sql_fetch);
}
Here is my code:
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
$conn=mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name'],$conn);
$exec_query =mysql_query($query) or die(mysql_error());
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
The Problem is that I am not getting anything in $row I cant get into the while loop, nothing shows up when I try to echo the value of $row, No error Nothing. Can you help me to find a problem in my code ?
Ps : The database is their. I have checked for the query for the corresponding value of $campagin_id. and also when i tried to echo $exec_query it echoed this : Resource id #8
PPS : The database have more than 7 record for each id so it doesn't matter if I call mysql_fetch_array($exec_query) more than once before going in to the while loop. and for the $campagin_id in the session their are many records present in the database.
You have written $row=mysql_fetch_array($exec_query) and then you are echoing something. and you are using the same in while.
Instead of:
$row=mysql_fetch_array($exec_query);
echo "<br> row = ".$row;
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
Use this (as per my knowledge you should not use $row=mysql_fetch_array() once you have used before while):
while ($row=mysql_fetch_array($exec_query)){
echo "I am In";
}
If the query returns Resource id #8 then that means it was successful - ie there were no errors. There were probably no rows returned by that query, so no rows in your table that match the given campagin_id.
You are also calling mysql_fetch_array() twice separately, you shouldn't do that because your while loop will skip the first row because calling this moves the pointer in the result set forward by one.
Also you can't echo an array as you are trying to, if you want to see the contents of an array use print_r() or var_dump().
I suggest adding some code to handle no rows found:
if($exec_query && mysql_num_rows($exec_query) > 0)
{
while ($row=mysql_fetch_array($exec_query)){
echo "Row: " . print_r($row, true);
}
}
else
{
echo 'None found';
}
Try this code.
<?
$campagin_id = $_SESSION['campagin_id_for_camp'];
$query = "SELECT * FROM survey_result where campagin_id = ".$campagin_id;
mysql_connect($dbconfig['db_hostname'],$dbconfig['db_username'],$dbconfig['db_password']) or die(mysql_error());
mysql_select_db($dbconfig['db_name']);
$exec_query =mysql_query($query) or die(mysql_error());
while ($row=mysql_fetch_assoc($exec_query)) {
echo "<br/> row = <pre>".print_r($row)."</pre><br/>";
}
?>
I'm working on a little system for SecondLife which involves a bit of heavy use of databases & I've run into a problem I can't for the life of me solve.
I'm trying to run a query that selects an entire row based on two different column values. I'm using the $_GET[''] call to identify which details I need, and then I need to pull all the data from the entire row and echo it onto a blank page.
Now, I got it to work at first, but it was pulling ALL the rows created by a UUID and echoing them, when I only needed a specific. Then I tried to get it to work with a second identifier (which is a column called 'field' for the purpose of testing), and that's pretty much where I lost it.
I just need to select one row that has two exact values, and I need it to be draconian so it only selects a row that has both and not just one of the two.
Any ideas?
Script enclosed (don't mind the mess or the commented out code which I kept for reference; I am going to clean the script once I get it working!)
<?php
// Get key from the parameter.
$avatar_key = $_GET['key'];
// Quest params.
$questname = $_GET['questname'];
$questid = $_GET['id'];
// Connect to the database. $con holds connection info.
$con = mysql_connect("localhost","user","pass");
// Error checking.
if(!$con)
{
die('Could not connect: '.mysql_error());
}
// Select the DB we want.
mysql_select_db("yyyyy_slcom",$con);
// Build the query.
$query = "SELECT * FROM sldb_data WHERE sldb_data.uuid = '$avatar_key' AND sldb_data.field = '$questname'";
/*$query = "select * from (
select uuid, field, value, progress, ROW_NUMBER() OVER (PARTITION BY uuid ORDER BY progress DESC)
";*/
// Run the query, store the result in variable $result.
$result = mysql_query($query);
if(!result)
{
die('Error: ' . mysql_error());
}
// Check how many rows we got back with our query.
$rows_returned = mysql_num_rows($result);
echo $row['field'];
// If we get anything back,
if($rows_returned > 0)
{
//echo $row['field'] . ' was found.' . $questname;
/*if(!$row['field'])
{
echo 'You are not on this quest yet.';
}
elseif(($row['field']) && ($row['value'] == "notstarted"))
{
echo 'This quest hasn\'t started yet.';
}
elseif(($row['field']) && ($row['value'] == "started"))
{
echo 'You are on quest: "' .$row['field']. '"';
}*/
/* $fields = mysql_list_fields("tenaar_slcom","sldb_data");
$columns = mysql_num_fields($fields);
for ($i = 0; $i < $columns; $i++) {$field_array[] = mysql_field_name($fields, $i);}
if(in_array($quest, $field_array))
{
echo 'Your quest is ' . $row['field'];
}
elseif(!in_array($questname, $field_array))
{
echo 'You are not on this quest yet.';
}
elseif((in_array($questname, $field_array)) && ($row['value'] == "notstarted"))
{
echo 'You have not started quest "' .$row['field']. '" yet.';
} */
// cycle through and print what we got.
//while($row = mysql_fetch_array($result))
//{
//echo 'Quest name: ' . $row['field'] . ' | Progress: ' .$row['value'] . '<br />';
//}
}
/*else
{
echo 'You are not on this quest yet.';
}*/
// Close the connection.
mysql_close($con);
?>
You appear to be missing a step in-between the time you get the number of rows and when you print out the field. You need to actually store the results of the query in the $row array.
$rows_returned = mysql_num_rows($result);
$row = mysql_fetch_array($result);
echo $row['field'];