This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I'm making php chat to my school project. Php code is divided to two files with code. First file is file, where is chat window and text input to enter message. This is the php code of first file:
<?php
$connection = mysql_connect('localhost', 'root', 'root');
if (!$connection) {
die('<b>Can\'t connect to database server. Error message: ' . mysql_error() . '</b>');
}
$database = mysql_select_db('vaclavik', $connection);
if (!$database) {
$command = 'CREATE DATABASE vaclavik';
if (mysql_query($command, $connection)) {
echo '<b>Database wasn\'t found. New one has been created. </b>';
mysql_close($connection);
$connection = new mysqli('localhost', 'root', 'root', 'vaclavik');
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created!');
}
else {
die('Can\'t create new table!');
}
}
else {
die('Database wasn\'t found and new one can\'t be created!');
}
}
mysql_close($connection);
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = 'SELECT * FROM chat';
$result = mysqli_query($connection, $command);
if(empty($result)) {
$command = 'CREATE TABLE chat(datum DATETIME, zprava TEXT)';
if (mysqli_query($connection, $command)) {
die('New table has been created');
}
else {
die('New table can\'t be created');
}
}
if (mysqli_num_rows($result) > 0) {
while($row = $result->fetch_assoc()) {
echo '<b>' . $row["datum"] . ":</b> " . $row["zprava"] . "<br />";
}
}
else {
echo '<b>No message found. Write something! :)</b>';
}
mysqli_close($connection);
?>
This code works. Then I created form to input message. It redirects to another file with php code to insert message into database. Problem is, if I put code with no error detections, it does nothing. And when I put there some error protetions, php starts report Parse errors with unexpected chars in code. Commonly '{' and 'echo'.
This is code of second file:
<?php
$message = $_POST["chatinput"];
$connection = mysqli_connect('localhost', 'root', 'root', 'vaclavik');
$command = "INSERT INTO chat (datum, zprava) VALUES (\'" . date("Y-m-d, h:i:sa") . "\', \'" . $message . "\')";
mysqli_query($connection, $command);
mysqli_close($connection);
echo "<script>window.location = \"../chat.php\"</script>";
?>
Related
This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 2 years ago.
I can't seem to get simple query working to find UserID from the table of Users by UserEmail
I have simple function to suppose to return UserID
functions.php
function get_userID($UEml)
{
// Check database connection
if( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$UEml = $DB->real_escape_string($UEml);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
if($qSQL) {
return array(status => true);
}
else {
return array(status => false, message => 'Not Found');
}
}
and I call it from php script
check-User.php
<?php
require_once("db-config.php");
include 'functions.php';
...
$UsID = get_userID("joe#example.com");
echo 'UserID: <span style="color: blue">'. $UsID ."</span>";
...
?>
db-config.php
<?php
// Two options for connecting to the database:
define('HOST_DIRECT', 'example.com'); // Standard connection
define('HOST_LOCAL', '127.0.0.1'); // Secure connection, slower performance
define('DB_HOST', HOST_DIRECT); // Choose HOST_DIRECT or HOST_STUNNEL, depending on your application's requirements
define('DB_USER', 'dbUser'); // MySQL account username
define('DB_PASS', 'SecretPas'); // MySQL account password
define('DB_NAME', 'DBName'); // Name of database
// Connect to the database
$DB = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($DB->connect_error) {
die("Connection failed: " . $DB->connect_error);
}
//echo "Connected successfully";
?>
I tried many variations, but no luck and also checked many similar posts here, but just can't get it working.
Thanks
You have a couple of errors here:
$DB is not available in the function
the echo statement is wrong
This is the code without these 2 errors:
function get_userID($DB, $UEml)
{
// Check database connection
if ( ($DB instanceof MySQLi) == false) {
return array(status => false, message => 'MySQL connection is invalid');
}
$qSQL = "SELECT UsID FROM Users WHERE UsEml=? LIMIT 1";
$qSQL = $DB->prepare($qSQL);
$qSQL->bind_param("s", $UEml);
$qSQL->execute();
$result = $qSQL->get_result();
while ($row = $result->fetch_row()) {
return $row[0];
}
// return $row[0];
// I do not know why you wrote this code. If you get an user this code will not be executed
if ($qSQL) {
return array(status => true);
} else {
return array(status => false, message => 'Not Found');
}
}
And your echo:
// ...
$UsID = get_userID($DB, "joe#example.com");
echo "UserID: <span style=\"color: blue\">{$UsID}</span>";
This question already has answers here:
Why shouldn't I use mysql_* functions in PHP?
(14 answers)
Closed 4 years ago.
Here is my php and mysql code. It don't show any data . please tell me where is my error:
<?php
$ddaa = mysql_query("SELECT ref FROM users WHERE id='$uid'");
$mallu2 = mysql_query("SELECT mallu FROM users WHERE id='$ddaa'");
$result = mysql_fetch_array($mallu2);
echo $result['mallu'];
?>
You can use Mysqli,mysql is deprecated
a little example:
conection to db test
$mysqli = new mysqli('127.0.0.1', 'user', 'password', 'test');
if ($mysqli->connect_errno) {
echo "Error: Errot on connection : \n";
echo "Errno: " . $mysqli->connect_errno . "\n";
}
// the query
$sql = "SELECT ref FROM users WHERE id=$uid";
//if don't have result
if ($resultado->num_rows === 0) {
echo "we can't find data with $uid. try again !.";
exit;
}
//print the result
while ($dato = $resultado->fetch_assoc()) {
echo $dato['ref'];
}
Mysqli Php documentation
This question already has answers here:
Warning: preg_replace(): Unknown modifier
(3 answers)
Closed 7 years ago.
I'm sure I'm just doing something stupid but I think I'm close. What I'm trying to do as add validation to my submission. With my current code regardless of what data I enter into the serial field it always comes up with Invalid Serial. Any suggestions?
<?php
$serial=$_POST['serial'];
$model=$_POST['model'];
$deviceCondition=$_POST['deviceCondition'];
$sealCondition=$_POST['sealCondition'];
$location=$_POST['location'];
$deployDate=$_POST['deployDate'];
$weight=$_POST['weight'];
$connectedTerminal=$_POST['connectedTerminal'];
$notes=$_POST['notes'];
//NEW PDO connection
$serialVal = "[a-zA-Z0-9-]+";
if ( preg_match( $serialVal, $serial ) ) {
try{
$conn = new PDO("mysql:host=$sql_server;dbname=$sql_db", $sql_user, $sql_pass);
$sql = "INSERT INTO web01dev4s2.ingenicoInfo (serial, model, deviceCondition, sealCondition, location, deployDate, weight, connectedTerminal, notes) VALUES ('".$serial."', '".$model."', '".$deviceCondition."', '".$sealCondition."', '".$location."', '".$deployDate."', '".$weight."', '".$connectedTerminal."', '".$notes."')";
$q = $conn->prepare($sql);
$result_1=($sql);
$q->execute();
}
catch (PDOException $pe) {
die("Could not connect to the database" . $pe->getMessage());
}
$count = $q->rowCount();
print("Saved $count record(s).\n");
header( "refresh:2;url=devicelist.php" );
}
else {
echo $serial . "Invalid serial number.";
}
?>
You forgot the delimiters "/"
if(preg_match("/[a-zA-Z0-9-]+/", $serial))
echo 'oui';
else
echo 'no';
Heres my code. Simple.
<?php
echo 'start<br>';
//Do the conntection
$checkconnection = mysql_connect('localhost', 'root', 'rootpass');
//Check if it's valid
if(!$checkconnection) {
echo 'CheckFailed';
} else{
echo 'CheckSucess';
}
echo 'end'; ?>
but I only can see 'start'. There is no 'CheckFailed', 'CheckSucess', 'end'
What should I do?
I already install mysql, create database, create tables, of course.
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}
$result = mysqli_query($con, "SELECT * FROM table;");
?>
This question already has answers here:
Error: file is encrypted or is not a database
(7 answers)
Closed 5 years ago.
I have an SQLite database and am trying to connect to it with PHP. This is what I'm using:
<?php
$dbconn = sqlite_open('combadd.sqlite');
if ($dbconn) {
$result = sqlite_query($dbconn, "SELECT * FROM combo_calcs WHERE options='easy'");
var_dump(sqlite_fetch_array($result, SQLITE_ASSOC));
} else {
print "Connection to database failed!\n";
}
?>
However, I get this error:
Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in C:\xampp\htdocs\deepthi\combadd\combadd_db.php on line 4
Connection to database failed!
What's wrong and how can I fix it?
Try to use PDO instead of sqlite_open:
$dir = 'sqlite:/[YOUR-PATH]/combadd.sqlite';
$dbh = new PDO($dir) or die("cannot open the database");
$query = "SELECT * FROM combo_calcs WHERE options='easy'";
foreach ($dbh->query($query) as $row)
{
echo $row[0];
}
$dbh = null; //This is how you close a PDO connection
Connecting To Database
Following PHP code shows how to connect to an existing database. If database does not exist, then it will be created and finally a database object will be returned.
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
?>
Now let's run above program to create our database test.db in the current directory. You can change your path as per your requirement. If database is successfully created then it will give following message:
Open database successfully
SELECT Operation
Following PHP program shows how we can fetch and display records
<?php
class MyDB extends SQLite3
{
function __construct()
{
$this->open('combadd.sqlite');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * FROM combo_calcs WHERE options='easy';
EOF;
$ret = $db->query($sql);
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
echo "ID = ". $row['ID'] . "\n";
}
echo "Operation done successfully\n";
$db->close();
?>
<?php
if ($db = sqlite_open('sampleDB', 0666, $sqliteerror) ) {
$result = sqlite_query($db, 'select bar from foo');
var_dump(sqlite_fetch_array($result) );
} else {
die($sqliteerror);
}
?>
Make sure sqlite support is enable, check phpinfo()
One another solution to your problem is:
Using sqlite3 module instead
class DB extends SQLite3
{
function __construct( $file )
{
$this->open( $file );
}
}
$db = new DB( 'sampleDB.sqlite' );