I have a working SQL statement that returned correct results when I checked it on MAMP.
SELECT `questions`.`questionID` AS question, `questions`.`questionText`,
`questions`.`categoryID`,`answers`.`answerID`,`answers`.`answerText`,
`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`
But I can't figure out how to print the output with php. Please help. This is the code:
<html>
<body>
<?php
header('Content-Type: text/html; charset=utf-8');
$con=mysqli_connect("localhost","root","root","Theory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questions'.'questionID'] . "}"; //this is not the full print
echo "{" . $row['questions'.'questionText'] . "}"; //just for chaking
echo "}";
}
mysqli_close($con);
?>
</body>
</head>
I get:"{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}{{}{}}" echoed.
You're executing a query again inside your if condition... But the $sql query is empty because the variable is not defined!
replace if (!mysqli_query($con,$sql)) with if (!$result) since you have already executed the query in the rows above.
EDIT to answer the question's comments:
when you're fetching the resulting array, you don't need to specify the table alias but just the column name OR the column alias if present.
Try this:
while($row = mysqli_fetch_array($result))
{
echo "{";
echo "{" . $row['questionID'] . "}"; //this is not the full print
echo "{" . $row['questionText'] . "}"; //just for checking
echo "}";
}
$sql is aparently not set. You can do:
$result = mysqli_query($con,"SELECT `questions`.`questionID` AS question, `questions`.`questionText`, `questions` .`categoryID`, `answers`.`answerID`,`answers`.`answerText`,`answers`.`isTrue`
FROM `questions`,`answers`
WHERE `questions`.`questionID` = `answers`.`questionID`");
if (!$result)
{
die('Error: ' . mysqli_error($con));
}
Related
So my 1st target is to convert expecting data from mySQL as JSON before use XML.
Things i trying to solve- Connect two tables from database for specific user and display it on screen.
Everything is in one PHP file:
<?php
include 'db.php';
session_start();
ob_start();
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM users
INNER JOIN user_quiz ON users.user_uid = user_quiz.user_uid
WHERE users.user_uid = '".$_SESSION['u_uid'] ."'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
// for check if record exist
echo "<br> id: ". $row["id"]. " - Name: ". $row["user_first"]. " " . $row["user_last"] . " id:" . $row["user_uid"] . " Selected qustion " . $row["q_topic"] . " ". $row["q_id"] . "<br>";
}
} else {
echo "0 results";
}
$myJSON = json_encode($outp);
echo $myJSON;
?>
So now where is a issue.. When i do SQL like that:
SQL:
$sql = "SELECT * FROM users";
PHP is convert data as JSON data... but when i trying to do that for specific user i have empty []... That's why i use echo to see if i have output or i have error but... i have displays value... Had no idea what's going on... need advice.
I am trying to figure out how to use this in a loop. Any help will be appreciated.
$conn = mysql_connect("localhost", "some_user", "password");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("some_db")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
$sql = "SELECT favid FROM ajaxfavourites";
$result = mysql_query($sql);
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
}
mysql_free_result($result);
Currently it displays results as:
116677889922
I need them to show them as (the way they are displayed in DB):
1166
7788
9922
PS I am aware that this function is deprecated, I am just trying to fix one of my older sites.
choose One of these ways:
echo $row["favid"]."<br>";
echo $row["favid"]."\n";
echo $row["favid"].PHP_EOL;
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"];
echo "\r\n";
}
You can simply echo the value with '<br/>' or '<p>' like following:
while ($row = mysql_fetch_assoc($result)) {
echo $row["favid"] . '<br/>';
}
OR
while ($row = mysql_fetch_assoc($result)) {
echo '<p>' . $row["favid"] . '</p>';
}
Also you can just put all favid into array and then in another loop, can customize how to show them, like following:
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row["favid"];
}
foreach($ids AS $idv) {
echo '<p>' . $idv . '</p>';
}
Ok, so I basically have an HTML form that consists of a hidden input and a submit button. When the button is pressed it will remove a specific row in my MySQL table. The code all actually does the function it should. However, I keep getting a syntax error displaying when I run it. Once I get the error, if I go back the row is gone, which is what I want. I am just not sure how to make it redirect after running like it should, rather than getting the error.
The error:
Error: 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 '1' at line 1
Line 1 seems fine to me (hence the confusion).
The PHP code that is running(campaignPostDelete.php):
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$postID = $_POST['postID'];
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=" . $postID);
if (!mysqli_query($con,$delete))
{
die('Error: ' . mysqli_error($con));
}
header("Location: index.php");
die();
mysqli_close($con);
?>
the HTML form with PHP in case it's needed:
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$campaignID = $_SESSION['campaignID'];
$result = mysqli_query($con,"SELECT posts.postID, posts.postDate, posts.postName, posts.postEntry FROM posts
INNER JOIN campaigns ON posts.campaignID= $campaignID
AND posts.campaignID= campaigns.campaignID ORDER BY postDate desc");
while($row = mysqli_fetch_array($result))
{
echo "<div id='campaignPostContainer'>";
echo "<ul class='campaignPostBox'>";
echo "<p class='postInfo'>";
echo "<form name='postDelete' action='campaignPostDelete.php' method='post'>
<input type='hidden' name='postID' value=" . $row['postID'] . ">
<input type='submit'>
</form>";
echo "Posted on:";
echo "<li>" . $row['postDate'] . "</li>";
echo "</p>";
echo "<p class='postInfo'>";
echo "Posted by:";
echo "<li>" . $row['postName'] . "</li>";
echo "</p>";
echo "<li class='postEntry'>" . $row['postEntry'] . "</li>";
echo "</ul>";
echo "</div>";
echo "<hr>";
}
mysqli_close($con);
?>
You are enclosing the ID in single quotes. It is an integer so shouldn't be enclosed in quotes.
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID='$postID'");
should be:
$delete = mysqli_query($con,"DELETE FROM posts WHERE postID=$postID");
However, you are also passing the connection string twice. So instead do this:
$delete = "DELETE FROM posts WHERE postID=$postID";
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
But this still leaves you vulnerable to SQL injection. Do at least this to improve this overall:
$delete = sprintf("DELETE FROM posts WHERE postID=%s", mysql_real_escape_string($postID));
if (!mysqli_query($con, $delete))
{
die('Error: ' . mysqli_error($con));
}
You'll also want to sanitize your other inputs.
I have this piece of code
<?
$db = pg_connect("host=h port=p dbname=dbn user=usr password=pass");
if ($db) {
echo 'Connection attempt succeeded.' . '<br>' . '<br>';
}
else{
echo 'Connection attempt failed.' . '<br>' . '<br>';
}
$query = "SELECT column1 FROM table";
$result = pg_query($db, $query);
while ($row = pg_fetch_array($result)) echo $row. '<br>'. '<br>';
echo pg_dbname($db). '<br>' ;
echo pg_get_pid($db);
?>
The result should be three numeric values. When I run it, all I get are three strings "Array".
Connection attempt succeeded.
Array
Array
Array
dbname
pid
Can anyone help, please?
DO:
while ($row = pg_fetch_all($result)) echo $row['column1']. '<br>'. '<br>';
OR debug:
while ($row = pg_fetch_all($result)) var_dump($row) . '<br>'. '<br>';
I am fetching data from mysql to a page, i am not sure if the way im doing it is appropiate. I am having trouble with fetching values into sections of the page.
<?php
// Connect to database server
mysql_connect("localhost", "xxx", "xxx") or die (mysql_error ());
// Select database
mysql_select_db("xxx") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM news";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
while($row = mysql_fetch_array($rs)) {
// Write the value of the column FirstName (which is now in the array $row)
echo $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
}
// Close the database connection
mysql_close();
?>
</div> <!-- content #end -->
the database;
the above yields;
I want to do the following;
BY: Fadi
echo 'BY' $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
but it isn't working :( any tips
You are missing a concat operator after 'BY'. Should be
echo 'BY' . $row['editor_name'] . " " . $row['news_desc'];
echo "<br />";
OR tidier:
echo "BY {$row['editor_name']} {$row['news_desc']}<br/>";
If you want to return associative array you can try using this line:
...
while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) {
...
You forgot one dot after 'BY'
echo 'BY' . $row['editor_name'] . ' ' . $row['news_desc'] . '<br />';