I am trying to make a query call from PHP. However, I am not sure why it is not working properly. It looks like there is something wrong with what I am trying to do with the query. Everything was working correctly before I added the where clause and the bindParam. The code is executing correctly and then stops after I make the query and the binding. Can someone see if I did that correctly?
Might have something to do with post call to gender. I could not echo out the $gender.
Thanks for any insights!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Practice Work 5</title>
</head>
<body>
<form action="babynames.php" method = "post">
Year:<br>
<input type="text" name="year">
<input type="submit" value="Submit">
</form>
<select name = "gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</body>
</html>
<?php>
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "baby";
$year = $_POST['year'];
$gender = $_POST['gender'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year = ? and Gender = ?";
$sql -> bindParam (1, $year, PDO::PARAM_INT);
$sql -> bindParam (2, $gender, PDO::PARAM_STR);
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Your variable $sql is string, not an object.
According http://php.net/manual/en/mysqli-stmt.bind-param.php
You have to prepare the statement before bind params like:
if ($stmt = $conn->prepare($sql)) {
$stmt->bind_param("is", $year, $gender);
$stmt->execute();
$result = $stmt->get_result();
$processedRows = 0;
while ($row = $result->fetch_assoc()) {
$processedRows++;
echo "<br> Year: ". $row["Year"]. " ; Name: ". $row["Name"]. " ; Ranking: " . $row["Ranking"] . " ; Gender: " . $row["Gender"]. " ". "<br>";
}
if (empty($processedRows)) { echo "0 results"; }
}
$conn->close();
Change this
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames where Year == ? and Gender == ?";
to
$sql = "SELECT Year, Name, Ranking, Gender FROM BabyNames WHERE Year = ? AND Gender = ?";
Related
I have something like this on my website. and I want to calculate the whole points of Sofia and show her the total balance. which is 163. but I am not getting how to add and then show her balance on my website. sorry, if it is too easy question. I am new to php.
here is the code
<form method="POST">
user name : <input type="text" name="username"><br>
Points to Add: <input type="number" name="blance" max="100"
min="1">
<br>
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$user = "root";
$password = "";
$database = "enter code here";
$con = mysqli_connect("$servername", "$user" , "$password" ,
"$database");
if ($con->connect_error) {
die ("connection failed" . $con->connect_error);
} else {
$username = mysqli_real_escape_string($con, $_POST['username']);
$blance = mysqli_real_escape_string($con, $_POST['blance']);
$sql = "INSERT INTO user (username, blance) VALUES ('$username',
'$blance')";
if ($con->query($sql) === TRUE) {
echo "success";
} else {
echo "error" . $sql . "<br>" . $con->error;
}
$sql6 = "SELECT * FROM user";
$result = mysqli_query($con, $sql6);
$resultcheck = mysqli_num_rows($result);
if ($resultcheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['username'] . "<br>";
}
}
echo "<br>" . "<br>" . "<br>";
}}
?>
</body>
This query will return sum of points for each username, assuming your table is named test
SELECT SUM(points) AS total_points
FROM test
GROUP BY username
<?php
$connect = mysqli_connect($hostname, $username, $password, $database);
$query = 'select stopname from greenline';
$result = mysqli_query($connect, $query);
?>
<html>
<body>
<form action="try.php" method="get">
<?php
echo "<select name='myselect'>";
while ($row1 = mysqli_fetch_array($result)):;
echo '<option value=" ' . $row1[0] . ' " name="row" >' . $row1[0] . '</option>';
endwhile;
echo "</select>";
?>
<input type="submit" name="submit"/>
</form>
<?php
if (isset($_GET['submit']))
{
$variable = $_GET['myselect'];
$query1 = 'select placeno from greenline where stopname = " ' . $variable . '"';
$result1 = mysqli_query($connect, $query1) or die(mysql_error());
$row2 = mysqli_fetch_assoc($result1);
echo "success";
$var = $row2['placeno'];
echo " this is $var";
} ?>
</body>
</html>
I have done as above in sublime.. it is not extract the variable value in our query.could you please give a solution.. $var is not being displayed
You have ; right after while. This makes your loop a no-op, basically.
Also remove : at the same place.
You have an extra space in the query:
$query1='select placeno from greenline where stopname = " '.$variable.'"';
^
Remove that space and it will work.
But it would be better if you used a prepared statement instad of substituting variables.
$stmt = mysqli_prepare($connect, 'select placeno from greenline where stopname = ?');
mysqli_stmt_bind_param($stmt, "s", $variable);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $placeno);
mysqli_stmt_fetch($stmt);
echo "this is $placeno";
You're also adding extra spaces in the html:
echo '<option value=" ' . $row1[0] . ' " name="row" >' . $row1[0] . '</option>';
^ ^
Get rid of these spaces as well.
I have a textbox that displays the current date in format: d-m-Y
<input type="text" name="date" class="form-control" value="<?php echo date('d-m-Y');?>"/>
When I save this the date will written to my database like: Y-m-d. For example: the current date is: 02-06-2016. My script writes this to the database as: 2002-06-16.
I am using the following code to save the data to my database:
<?php
session_start();
$correct = true;
$date = $_POST['date'] ;
if($correct){
$db = new PDO('mysql:host=localhost;dbname=db', 'root', '');
$query = "INSERT INTO table(date) VALUES (?)";
$stmt = $db->prepare($query);
$stmt->execute(array($date));
header('Location: ./index.php');
}
else
{
echo "Error";
}
?>
What do I need to change in my code so it will post it like: 2016-06-02 Y-m-d or 02-06-2016 d-m-Y?
If d-m-Y is not possible, how can show the data that is written like Y-m-d in the database show as format d-m-Y in my php script?
Edit:
For selecting the date I use:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";
$sql = date("d-m-Y",strtotime($row['date']));
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td>" . $row["id"]. "</td>";
echo "<td>" . $row["date"]. "</td>";
}
} else {
echo "<p> </p>";
}
$conn->close();
?>
$date = $_POST['date'] ;
$date = date("Y-m-d",strtotime($date));
To show date in d-m-Y format in HTML page, again convert it into
$date = date("d-m-Y",strtotime($row['date']));
[Note: I'm assuming your fetch array as $row and column as date.]
For more info, please have a look on strtotime - php manual
Update Code (As question is edited)
$sql = "SELECT * FROM table WHERE id='1' ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<td>" . $row["id"]. "</td>";
echo "<td>" . date("d-m-Y",strtotime($row['date'])). "</td>";
}
} else {
echo "<p> </p>";
}
$conn->close();
I am trying to write a php code that changes the availability of a certain apartment. Here is my code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$servername = "localhost";
$username = "bla";
$password = "blabla";
$dbname = "testDB";
// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}else{
echo "Connected successfully to the database: " . $dbname . "<br><br>";
}
$query = "SELECT * FROM test";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo "id: " . $row["id"] . " // Address: " . $row["address"] . " // Rooms: " . $row["rooms"] . " // Availability: " . $row["availability"] . ".<br>";
?>
<form method ="post" action ="<?php $_PHP_SELF ?>">
<input name="update" type="submit" value="Change Availability">
</form>
<?php
if(isset($_POST["update"])) {
$avail = mysqli_query($connect,"SELECT availability FROM test WHERE id='1'");
$availCheck = mysqli_fetch_array($avail);
settype($availCheck, "int");
if($availCheck == 1){
$upAvail = mysqli_query($connect,"UPDATE test SET availability='0' WHERE id='1'");
}else{
$upAvail = mysqli_query($connect,"UPDATE test SET availability='1' WHERE id='1'");
}
}
?>
</body>
</html>
And this is the output I get:
Connected successfully to the database: testDB
id: 1 // Address: 3787 cote des neiges // Rooms: 2 // Availability: 1.
Change Availability
So here is my issue. When the availability is 1 and I press the button it changes to 0. But after that, when I press the button again, it doesn't change back to 1.
Why is that?
Thank you for the help.
You're not toggling the availability. The mysqli_fetch_array fetches the row from the test table matching the id (id=1). As a result, $availCheck will always equal 1 after you cast the non-empty array to an integer.
You can replace all that logic with a single MySQL query to toggle the value.
UPDATE test SET availability = IF(availability = 1, 0, 1) WHERE id=1
I think what you wanted to do:
$availCheck = mysqli_fetch_array($avail)['availability'];
I need help on how to do this correctly. I need to execute this command:
SELECT concat(branchname, -->, itemtype, '(, quantity, ')') from monitoring
order by itemtype;
the syntax works in MySQL console. However, im having trouble with implementing it on php. I always get
"Undefined index: branchname"
"Undefined index: itemtype"
"Undefined index: quantity"
using this code:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
The error says it's in this line
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
Im confused because I basically ran the same code that worked that lets me see the itemtype in the table:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dex_test";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT itemtype FROM monitoring";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "itemtype: " . $row["itemtype"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
Help anyone?
It seems your query needs update
"SELECT concat(branchname,itemtype,quantity) from monitoring order by itemtype";
It should be
"SELECT branchname,itemtype,quantity from monitoring order by itemtype";
I have posted this answer in reference of how you were calling your fields in while loop
echo " " . $row["branchname"]. " " . $row["itemtype"]. " ".$row["quantity"]. "<br>";
and if you need to show the concat value within one field than it should be something like
$sql = "SELECT concat(branchname,' ',itemtype,' ',quantity) as branch from monitoring order by itemtype";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo $row["branch"]."<br>";
}
} else {
echo "0 results";
}
Just define the alias for the concatenated columns. Use this -
SELECT concat(branchname,itemtype,quantity) as branchname from monitoring order by itemtype
Or if you want them seperately then -
SELECT branchname, itemtype, quantityfrom monitoring order by itemtype