querying mysql database using php - php

I've searched google and on here and some info has been useful but mostly not so useful and still can't manage to query my database using php.
I'm very new to coding so thought it best to find an answer based on my code rather than other peoples slightly different problems.
I have a small database, people fill in a form who wish to hire a bus. i have created a calendar and wish to print out for each day what time and for how long there is a hire, if there is one, based on the data people have entered which has been sent to my database.
The whole page shows but the calendar contains an error within its table saying:
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''2013-03-01' at line 1"
even if i delete the "where date=.." part of the query it continues to show this.
ive tried several different methods of writing the code out, including a loop and not including one but im not really sure what im meant to do.
EDIT: MY CODE IS NOW:
<?php
$con = mysql_connect("localhost","user","password");
$result = mysql_query("SELECT time, length FROM hire WHERE date='01-03-13'");
$row = mysql_fetch_assoc($result);
$Time = $row['TIME'];
$Length = $row['LENGTH'];
echo "Time: " . $TIME . "<br/>";
echo "Length: " . $LENGTH . "<br/>";
?>
I now get the error "Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in C:\Users\Laura\Documents\COMPY\server\www\calendar.php on line 123"
It shows the page, calendar and "time" and "length" but with the error and no data
EDIT
<?php
$con = mysql_connect("localhost","user","password");
mysql_select_db("busassociation", $con);
$result = mysql_query("SELECT time, length FROM hire WHERE date='01-03-13'");
while ($row = mysql_fetch_assoc($result)){
$time = $row['time'];
$length = $row['length'];
echo "time: " . $time . "<br/>";
echo "length: " . $length;
}
?>

use backticks
$result = mysql_query("SELECT `time`, `length` FROM `hire` WHERE `date`= '2013-03-01' ");
EDIT.
your are fetching your query two times.
$row = mysql_fetch_row($result); <------- delete this line
while( $row = mysql_fetch_row($result) ){
EDIT.2
i think u dont reconize the diference between
mysql_fetch_assoc() and mysql_fetch_row()
if you use mysql_fetch_assoc() it will be correct in your code.
but if u use mysql_fetch_row() as u have done in your code u must echo values like that
$Time = $row['1']; // suppose that `TIME` is the second column
$Length = $row['2']; // suppose that `LENGTH` is the third column
EDIT.3
<?php
$con = mysql_connect("localhost","user","password");
mysql_select_db("your_db", $con); <---------replace by your database
$result = mysql_query("SELECT time, length FROM hire WHERE date='01-03-13'");
while ($row = mysql_fetch_assoc($result)){
$Time = $row['time'];
$Length = $row['length'];
echo "Time: " . $Time . "<br/>";
echo "Length: " . $Length . "<br/>";
}
?>

Related

Make PHP array from numerical data in MySQL table and multiply it

Good day,
I'm a noob at PHP and MySQl. Looking to be pointed in the right direction.
I have a MySql table with 5 columns. Each column represents a specific set of data. All numerical.
I want to write PHP code which takes each value in a single column and puts it into an array that I can then modify.
I don't know how to get each column as a separate array. Should I get an array of all the rows and then do something extra to separate each of the 5 numbers in each row into 5 separate arrays?
**
require_once 'login.php';
echo $db;
$conn = mysqli_connect($hn,$un,$pw,$db);
if (!$conn) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
$query = "SELECT xox FROM tablex WHERE id = '1'";
$result = $conn->query($query);
if(!$result) die ("Database access failed: " . $conn->error);
$rows = mysqli_fetch_row($result);
while($rows){
echo $rows['index'];
}
echo $rows[0];
?>
$statement = **yourDatabaseConnection**->query('SELECT column1 FROM table');
$datas = $statement->fetch();
$datas will be an array of your column1 datas
Try reviewing the php documentation, here is a good place to start...php:mysql_fetch_row
Take a look at the example below, if is not what you looking for, please edit your question and provide the approach you are taking (your code) so that we have a better understanding where you are having issues.
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>

Creating An Array from MYSQLI query

I am updating all my code to Mysqli, before I did I had this code and it worked:
while($row = mysql_fetch_assoc($WildHorses)){
$InWild[] = $row['id'];
}
$RandomWild = array_rand($InWild);
$RandomHorse = $InWild[$RandomWild];
This is my SELECT statement:
$sql = "SELECT Horse.id, Horse.Name, Horse.Age, Horse.Image_name, Horse.Owner, Horse.Barn, Images.Image_path, Images.Image_name FROM Horse, Images WHERE Horse.Owner = '$colname_WildHorseList' AND Images.Image_name = Horse.Image_name";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " Name: " . $row["Name"]. " ImageName: " . $row["Image_name"]. "<br>";
}
} else {
echo "0 results";
}
The SELECT statement ends up echoing all of the correct information, but I want to make an array of only the Id's so that I can pick one at random each time a button is clicked.
I have tried multiple different copies and pastes of code to try and get what I want, but nothing seems to come out right.
Can someone point me in the right direction or explain what I'm doing wrong?
In your while loop you can simply do this :-
$i=0;
$animals=array();
$animals[$i]=$row["id"]; //puts id in array
And then you can create a random number by "rand()" between the length of 0-$i
and can get the job done.

Simple query not pulling from database

I cannot figure this out, it's not an error as such, but when i try to echo out the results of a query:
echo "SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'" . "<br />";
$q = mysql_query("SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'");
$a = mysql_fetch_array($r);
$n = mysql_num_rows($q);
echo "Number of rows:" . $n;
echo $a['cus_id'];
echo $a['cus_email'];
The number of posts is returning the correct number which is 1, these values $a['cus_id']; and $a['cus_email']; are not coming through at all, i even did a mysql query in phpmyadmin and it works there.
can anyone see what i have done wrong?
correct code can be
echo "SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'" . "<br />";
$q = mysql_query("SELECT * FROM `active_customers` WHERE `cus_email`='".$k."' AND `cus_product`='".$_GET['product']."'");
$n = mysql_num_rows($q);
echo "Number of rows:" . $n;
while($row = mysql_fetch_array($q, MYSQL_ASSOC)){
echo $row['cus_id'];
echo $row['cus_email'];
}
Although i would recommend using mysqli or PDO for sql databases

Return Specific Row From DB

I have multiple links on a page where each link is suppose to return a specific row of data from a database. When the link is clicked, the user is forwarded to another page where the info associated with that link is displayed. Here is the code:
//db connection: (using xampp)
mysql_connect('localhost', 'root', '');
mysql_select_db('db_name');
$sql = "SELECT * FROM user_input";
$records = mysql_query($sql);
//code:
<div>
$open_report = mtsql_fetch_assoc($records);
echo "Error Report# {$open_report['id']};
echo "<p>" .$open_report['comments'] . "</p>";
</div>
The problem is it always returns the same row of data. Each row in the db is associated with a link and when that link is clicked I want to return the associated row of data in the db. I think it may have to do with this line: $sql = "SELECT * FROM user_input"; but I'm not sure how to fix it. If anyone can help it would be greatly appreciated.
I have restructured my answer to give it a better flow. I also noticed you are using mysql_ not mysqli_ . You need to use mysqli_ as mysql is depreciated.
EDIT: This would be the page that displays all the error reports. You would want to output them in the form of a hyperlink that passes a GET parameter to the page that shows the details.
$sql = "SELECT ID, Description, etc, etc from reports";
$open_reports = mysqli_query($sql);
//error check here as well if ANY results were returned
while($row = mysqli_fetch_array($open_reports, MYSQLI_ASSOC)) {
echo ''' . $open_reports['Description'] . '';
}
This will give you links that look like
detailspage.php?id=1 detailspage.php?id=2
etc...
On the "detailspage.php" You can capture that ID and display dynamic information on that same page.
if (isset($_GET['ID'])){
$sql = "Select * from user_input where ID='" . $_GET['id'] . "'";
$records = mysqli_query($sql)
while($open_report = mysqli_fetch_array($records, MYSQLI_ASSOC)) {
echo "Error Report# " . $open_report['id'] . "<br/>";
echo "<p>" .$open_report['comments'] . "</p>";
}
}

Recalling random values from mysql table

I'm fairly new to php and mysql and I'm on the home stretch of finishing my page but I've been banging my head on the keyboard all day trying to figure out how to fix this problem. I've set up a php script to run as a cron even every 24 hours. The script assigns a random number between 10 and 30 to each field in my table. That works fine and every time I load the script the values change.
The problem I'm having is when I try to use those values. The result keeps printing as the word Array instead of the number in the table. So I'll give you some snippets of the code I'm running here. This is the cron event.
?php
$con = mysql_connect("localhost","username","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dbname", $con);
$random= rand(10, 30);
mysql_query("UPDATE winners SET pool= '$random'");
mysql_close($con);
And here is the script to call up the values.
php?
$db = mysql_connect('localhost','username','pass') or die("Database error");
mysql_select_db('dbname', $db);
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
if ( $row % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
I've tried every possible variation I can think of to this code but all I can get is it to echo either Array or Resource #9. Any insight into this would be greatly appreciated.
You do not want to echo the content of $row, which contains all data returned for the current line you've fetched from the database when calling mysql_fetch_array().
Instead, you want to access the content of $row's pool item :
echo $row['pool'];
You should probably take a closer look at the manual page for mysql_fetch_array(), and the examples it contains.
Note that you'll probably also want to modify the condition in the following line :
if ( $row % 2 )
You probably don't want the test to be done on $row, but on an item it contains.
$query = "SELECT pool FROM winners";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
if ( $row['pool'] % 2 )
{
echo "<h4>Result 1</h4>";
echo "$row['pool']";
echo "<br />";
}
else
{
echo "<h4>Result 2</h4>";
echo "<br />";
}
}
Hope this helps.

Categories