echo doesnt work after pg_query - php

I'm currently trying to retrieve information from my database and display this data with a php file but it doesnt work as intended. Here is my code:
<?php
require("dbconnect.php");
if(!$db){
echo "Error: Unable to open database";
} else {
echo "Opened database successfully";
}
$result = pq_query($db, 'SELECT * FROM example');
if (!$result) {
echo "Error: Cant access table";
exit;
}
else {
echo "Everything works fine";
}
pg_close($db);
?>
Note: dbconnect.php opens the connection to the database with pg_connect() and saves this to $db.
I expected that it displays Opened database successfully Error: Cant access table because I havent created a table example yet. But I only get Opened database successfully. So I added echo "Test"; before pg_close($db); and expected that it displays Opened database successfully Test but no, it only shows Opened database successfully.
I then tried to create a new table with php so I added
pg_query($db, 'DROP TABLE IF EXISTS example');
pg_query($db, 'CREATE TABLE example (col char(1))');
before $result = pq_query($db, 'SELECT * FROM example');. I connected with ssh to the server after this and checked with psql if the table exists and it did, so the connection should work properly. But it still only shows me Opened database successfully and I expected Opened database successfully Everything works fine. I really dont know why every echo after $result = pq_query($db, 'SELECT * FROM example'); doesnt work. Can someone explain to me whats wrong?

Change pq_query for pg_query.
Note you have a Q instead of a G.

Related

SQL command is executing but is returning false in the mysqli connection

I have a web page created in php using html code. I want to save user information entered in my web page to a MySQL database. I am using php as the middle man to link the frontend web page(htmnl code) to the database(mysql).
Inside my link folder (middle man php file) I have the following:
<?php
//Gets server connection credentials stored in serConCred2.php
require_once('ConCred2.php');
//SQL code for connection w/ error control
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if(!$con){
die('Could not connect: ' . mysqli_connect_error());
}
//Selection of the databse w/ error control
$db_selected = mysqli_select_db($con, DB_NAME);
if(!$db_selected){
die('Can not use ' . DB_NAME . ': ' . mysqli_error($con));
}
//Co-PI and Co-Investigator Information variables
$Co_FNAME = $_POST['fname'];
$Co_LNAME = $_POST['lname'];
$Co_SLNAME = $_POST['slname'];
$Co_DEGREE = $_POST['Degree_Selection'];
$Co_DEGREE_Other = $_POST['other_specify_degree']; //hold the value of degree if user selected other from the dropdown menu
$Co_CPOS = $_POST['Current_Position_Selection'];
$Co_CPOS_Other = $_POST['other_specify_cpos']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_INST = $_POST['Institution_Selection'];
$Co_INST_Other = $_POST['other_specify_inst']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_SCHOOL = $_POST['School_Selection'];
$Co_SCHOOL_Other = $_POST['other_specify_school']; //hold the value of Current Position if user selected other from the dropdown menu
$Co_DEPART = $_POST['Department_Selection']; //Este se estara eliminando en la version online
$Co_DEPART_Other = $_POST['other_specify_department']; //hold the value of Department if user selected other from the dropdown menu
$Co_PROGRAM = $_POST['program'];
$Co_EMAIL = $_POST['email'];
$Co_PHONE = $_POST['phone'];
//If decition when user select other from the dropdown menu
if($Co_DEGREE == "other_degree") $Co_DEGREE = $Co_DEGREE_Other;
if($Co_CPOS == "other_cpos") $Co_CPOS = $Co_CPOS_Other;
if($Co_INST == "other_inst") $Co_INST = $Co_INST_Other;
if($Co_SCHOOL == "other_school") $Co_SCHOOL = $Co_SCHOOL_Other;
if($Co_DEPART_Other == "other_department") $Co_DEPART = $Co_DEPART_Other;
//This sets a starting point in the rollback process in case of errors along the code
$success = true; //Flag to determine success of transaction
//start transaction
echo "<br>1. Going to set autocommit to 0";
$command = "SET AUTOCOMMIT = 0";
echo "<br>2. Autocomint has been set to 0";
echo "<br>3. Going to run query to see if result is true or false";
$result = mysqli_query($con, $command);
echo "<br>4. Finished running the query. Result is:" . $result;
echo "<br>5. Going to set command to BEGIN";
$command = "BEGIN";
echo "<br>6. Command is now BEGIN";
echo "<br>7. Going to run query for command BEGIN";
$result = mysqli_query($con, $command);
echo "<br>8. Query runned for command BEGIN";
echo "<br>9. Result value is: " . $result;
//Saves Pi values into database
/**
$sqlCoPI = "INSERT INTO co_pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
echo "<br>10. Going to write sql command to populate table pi_table";
/**
$sqlPi = "INSERT INTO pi_table (Fname, Lname, SLname, Degree, Current_Position, Institution, School, Department, Program, Email, Phone)
VALUES('$Co_FNAME', '$Co_LNAME', '$Co_SLNAME', '$Co_DEGREE', '$Co_CPOS', '$Co_INST', '$Co_SCHOOL', '$Co_DEPART', '$Co_PROGRAM', '$Co_EMAIL', '$Co_PHONE')";
*/
$sqlPi = "INSERT INTO pi_table (Fname) VALUES('$Co_FNAME')";
//Checks to see if theres an error in the pi db con
echo "<br>11. Sql command finished writting.";
echo "<br>12. Going to query the sql finished command to the database to determine value of result.";
$result = mysqli_query($con, $sqlPi);
echo "<br>13. Finished running sql command to database. Result value is: " . $result;
echo "<br>14. Going to enter if statements depending on result value";
if($result == false){
//die ('<br>Error in query to PI table: ' . mysqli_error($con));
echo "<br>15. I am inside the false statement. Success is going to be set as false. ";
$success = false;
//$success = true; //Cahnged this in order to test if values are being saved to db. Change back to false.
}
//Checks for errors or craches inside the code
// If found, execute rollback
echo "<br>16. Going to verify is success is true.";
if($success){
$command = "COMMIT";
$result = mysqli_query($con, $command);
//echo "<br>Tables have been saved with 0 errors.";
echo "<br><p style=\"color: red;\"Principal Investigator has been saved successfuly. <br><br>
You may now CLOSE this page and press the<br><br> \"Refresh List\" <br><br>
button to display name in dropdown menu selection.</p>";
}
else{
$command = "ROLLBACK";
$result = mysqli_query($con, $command);
echo "<br>17. Success was determined to be false.";
echo "<br>Error! Databases could not be saved.<br>
Contact system manager to report error. <br> <br>" . mysqli_error($con);
}
echo "<br>18. Setting autocommit back to 1 again.";
$command = "SET AUTOCOMMIT = 1"; //return to autocommit
$result = mysqli_query($con, $command);
//Displays message
//echo '<br>Connection Successfully. ';
//echo '<br>Database have been saved';
//Close the sql connection to dababase
mysqli_close($con)
?>
As you can read, I am requiring users to fill out their information. Some of the information required are dropdown menu fields that user selects an option from among the presented ones.
The problem I am having is, when the above php code executes, it determines that the $result variable is false and doesn't save anything. When you execute the code, you get the following messages displayed:
1. Going to set autocommit to 0
2. Autocomint has been set to 0
3. Going to run query to see if result is true or false
4. Finished running the query. Result is:1
5. Going to set command to BEGIN
6. Command is now BEGIN
7. Going to run query for command BEGIN
8. Query runned for command BEGIN
9. Result value is: 1
10. Going to write sql command to populate table pi_table
11. Sql command finished writting.
12. Going to query the sql finished command to the database to determine value of result.
13. Finished running sql command to database. Result value is:
14. Going to enter if statements depending on result value
15. I am inside the false statement. Success is going to be set as false.
16. Going to verify is success is true.
17. Success was determined to be false.
Error! Databases could not be saved.
Contact system manager to report error.
18. Setting autocommit back to 1 again.
For security purposes I cant post the html content since it has sensitive name information nor the databases. Although I can ensure that the tables inside the database are called exactly as mentioned in the sql command line.
I HAVE FOUND THE PROBLEM!
After long debating I decided to recreate the database In which all the information was being stored. When I redirected the table in my sql command ( Instead of saving it in "pi_table" I saved it in a newly created database called "pi_table_2") and everything worked out properly.
Aparently my database got corrupted and phpMyAdmin didn't recognized that it was curropted.
For reference my database tables where in InnoDB format. What might have cause this to happen, who knows but if you ever encounter a similar problem, creating a small testing database and see if it saves. If it does, recreate the table and it might solve your issue like it solved mine.
Once again thank you a lot guys!!!!!
I am looking at the code and everything seems to be in order, could be a syntax error like a missing quotation for example:
//SQL code for connection w/ error control
$con = mysqli_connect("DB_HOST", "DB_USER", "DB_PASSWORD", "DB_NAME");
also
$db_selected = mysqli_select_db($con, "DB_NAME");
or die ("Cant select Database");
}
Hope this help.
Cheers;
Hasan

How to store <li>-item created by user server sided (mySQL)

I have a simple <ul> where you can add a list item with an input field:
$('#plannerform').submit(function(e) {
var val = $(this).find('#plannername').val();
$('ul.plannerlist:visible').append('<li>' + val + '</li>');
e.preventDefault();
});
My question is: Is it possible in a way to save this created list on a mySQL database on a webserver? I haven't got much experience in PHP or other languages for server sided storage. And if it's possible, can you tell me any links where it's explained how? I spent some time already with searching, but I didn't find anything because I simply don't know what to search after.
Here is a simple php script that I wrote to connect to my MySQL DB, and retrieve along with display each result in a given column.
Just replace:
Hostname with probably your local IP if MySQL is installed on your local machine.
Your MySQL username, probably root if you haven't created another user.
The password, which could be blank if you didn't create one.
Database with the name of your Database.
<?php
//Connect to DB
$conn = new mysqli("Hostname","Username","Password","Database");
//If the connection has errors
if ($conn->connect_error){
//Display the error
die("Connection failed because: " . $conn->connect_error);
}
//Otherwise the connection is good so lets create a sql query
$sql = "SELECT * FROM Database";
//Get the results of the query
$result = $conn->query($sql);
//If the results have rows
if($result->num_rows > 0){
//While there are more rows in the results
while($row = $result->fetch_assoc()) {
//Display in HTML paragraph form: Column1 = DataInColumn1
echo '<p> Column1 = ' . $row["Column1"] . ' </p>';
}//End While
}//End If
//Otherwise the query had no results
else{
echo '<p>No results found!</p>';
}
?>

update table in sql not working

I am tring to update data of private_tutor Table. But its not working .
But when I write the sql command
(UPDATE private_tutor SET name='private' , contact_number='0000' ,
address='dw', experience='s',
qualification='dwd' , age='dwd', about='dwd'
WHERE id=1)
in terminal it updates , table.
What may be the reason , I am giving the same query through php. why its not working ?
output
UPDATE private_tutor SET name='private' , contact_number='0000' , address='dw', experience='s', qualification='dwd' , age='dwd', about='dwd' WHERE id=1
There is some problem in adding record
update.php
<?php //start php tag
//include connect.php page for database connection
include('connect.php');
include('session.php');
//if submit is not blanked i.e. it is clicked.
Echo $_GET['profile-name'].$_GET['profile-contact'].$_GET['address'].$_GET['experience'].$_GET['qualification'].$_GET['age'].$_GET['about'].$_GET['id'];
If(isset($_GET['submit']))
{
$sql="UPDATE private_tutor
SET name='".$_GET['profile-name']."' ,
contact_number='".$_GET['profile-contact']."' ,
address='".$_GET['address']."',
experience='".$_GET['experience']."',
qualification='".$_GET['qualification']."' ,
age='".$_GET['age']."',
about='".$_GET['about']."'
WHERE id=".$_GET['id']." ";
echo "</br>".$sql."</br>";
$res=$conn->query($sql);
If($res)
{
header('Location:private-tutor-profile.php');
}
Else
{
Echo "There is some problem in adding record";
}
}
?>
Instead of outputting your own error message which tells you next to nothing about the problem, output the error message from the database connection.
So instead of this line
Echo "There is some problem in adding record";
Do this instead:
If $conn is PDO
echo print_r( $conn->error_info );
If $conn is MYSQLI_
echo $conn->error;
But quite possibly, your connection has failed and you do not show us that code!! And I assume you are not looking for error messages there either.

Table exists in PHPmyAdmin but does not appear using SHOW TABLES query in PHP

I am a new user to stackoverflow, I did do a search for similar questions and I found a many, but none were resolved in a way that helped me. So that's why I'm asking this even though it may be a duplicate. (This one for example seems to be the same problem I'm having: MySQL table exists on server but cannot access it from PHP)
I created a table (members) in my database (test) using PHPmyAdmin. If I do an SQL query there to SHOW TABLES FROM test, the table "members" is listed. However, PHP does not seem to be able to access it. This is my file access_test_table.php:
<html>
<body>
Testing.<br>
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
echo "The host is $host<br/>";
echo "The username is $username<br/>";
echo "The password is $password<br/>";
echo "The db name is $db_name<br/>";
echo "The table name is $tbl_name<br/>";
// Connect to server and select databse.
$con=mysqli_connect("$host","$username","$password","$db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
echo "<br/>";
}
else {
echo "Connected to database.<br/>";
}
//Want to show the tables in the database
$query_1="SHOW TABLES FROM $db_name'";
$result_q1 = mysqli_query($con,$query_1);
if (!mysqli_query($con,$query_1))
{
echo("Errorcode: " . mysqli_errno($con));
echo "<br/>";
}
else {
echo "The following tables are in the database: " . $result_q1;
echo "<br/>";
}
mysqli_close($con);
echo "Connection closed.";
?>
</body>
</html>
I checked that "username" is the same user as was used to create the table and has the right permissions to access it. I also updated to using no mysql_* commands but rather mysqli_* ones. Finally, I tried using mysqli_multi_query, but the result is the same. This is the output of the code on the page:
Testing.
The host is localhost
The username is username
The password is password
The db name is test
The table name is members
Connected to database.
Errorcode: 1064
Connection closed.
Can someone suggest to me how I can fix this? Thanks!
Remove the ' from the Query:
$query_1="SHOW TABLES FROM $db_name'";
So it looks like this:
$query_1="SHOW TABLES FROM $db_name";
Credits to Fred (Posted as Community Wiki to close the Question)

PHP cannot find tables even after successfully connecting to the database

The below code re-creates the issue I can't get around. I just can't seem to figure out where the problem lies - in the code? MySQL settings? or somewhere else? Any pointers in the right direction will be appreciated.
<html>
<head></head>
<body>
<?php
$db_name = "UserDB";
$open = mysql_connect("localhost", "root", "");
if($open)
echo "1. Successfully connected to MySQL";
echo "</br>";
$db = mysql_select_db($db_name, $open);
if($db)
echo "2. Successfully selected {$db_name} database";
echo "</br>";
$sql = "SHOW TABLES FROM `{$db_name}`";
$result = mysql_query($sql);
$print = mysql_num_rows($result);
if($result)
echo "3. {$print} tables found in {$db_name}";
?>
</body>
</html>
Here's my output:
1. Successfully connected to MySQL
2. Successfully selected UserDB database
3. 0 tables found in UserDB
The problem lies in line 3 of the output. It says "0" tables, which is incorrect. I have created "3" InnoDB tables in the selected DB. If I copy/paste and run the same SHOW TABLES query in phpmyadmin, it runs perfectly.
Any idea what is going on here??
Try using the wrapper function mysql_list_tables. I found it impossible once to use the SHOW TABLES due to some weird permissions definition, though I could use mysql_list_tables.

Categories