I have been banging my head against a wall for hours now, reading several answers on SO, searching the 'net, trying to find a solution. While I realize similar questions have been asked and answered here, my code is different so I can't extrapolate from previous answers what's wrong with mine.
I'm new to PHP/MySQL. I have a poll script that I patched together using some code I found online and my own knowledge; the MySQL is mine, standard stuff. Each time a person votes for one of two things, its corresponding value in the database in increased by one. I'm trying to retrieve and assign each value to its own variable and perform a calculation. I can retrieve the first one just fine, but I get the dreaded
Trying to get property of non-object in..." error and
"Fatal error: Call to a member function bind_param() on a non-object in...
for the second one. It's exactly the same as the first prepare, so I'm not sure what's wrong? This may not be the most efficient way to do this, but like I said, I'm new to this. I DO understand what the error is trying to convey; I just don't understand why I'm getting the error when the prepare statement is identical to the one before it except for the id in the WHERE clause. var_dump($query2) returns bool(false), so I can clearly see nothing is there. But there IS something in the database.
<?php
// Turn on error reporting
ini_set('display_errors', 'On');
// Connect to database
$mysqli = mysqli_connect('localhost', 'dbuser', 'dbpwd', 'dbname');
// Check connection
if (!$mysqli || $mysqli->connect_errno)
{
echo "Connection error: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
exit();
} else if (isset($action)) // This is set through a page redirect
{
// DISPLAY ITEM - THIS WORKS FINE
if (!($query = $mysqli->prepare("SELECT votes FROM influential WHERE id = 1")))
{
echo "Prepare failed: " . $query->errno . " " . $query->error;
}
if (!$query->execute()){
echo "Execute failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
if (!$query->bind_result($infl1))
{
echo "Bind failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
if ($query->fetch())
{
echo $infl1;
}
// DISPLAY ITEM - THIS DOESN'T WORK
if (!($query2 = $mysqli->prepare("SELECT votes FROM influential WHERE id = 2")))
{
echo "Prepare failed: " . $query2->errno . " " . $query2->error;
} else echo "Prepare succeeded.";
$query2->bind_param("i", $votes);
if (!$query2->execute()){
echo "Execute failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
} else echo "Execute succeeded.";
if (!$query2->bind_result($infl2))
{
echo "Bind failed: " . $mysqli->connect_errno . " " . $mysqli->connect_error;
} else echo "Bind succeeded.";
if ($query2->fetch())
{
echo $infl2;
}
exit();
$mysqli->close();
}
?>
In mysqli, when you issue the command:
.bind_param()
you are binding parameters to placeholders in the original query, not in the result. Your select query should read:
SELECT `votes` FROM `influential` WHERE `id`=?;
Then, you use bind_param to bind an integer to the placeholder, thusly:
.bind_param('i', $id);
After calling .execute(), the result is bound using references by calling .bind_result(). Whatever variable you pass into .bind_result() will contain the data afterwards.
Cheers
Related
I am trying to create an php script which can read and array list from android and read it's element and store it in data base, now I have been able to store the data in an text file but unable to proceed further, could some body help me out in this matter?
this is the php script which I have used:-
<?php
$i=0;
$password="";
$user="root";
$database="shadowpets";
$host="localhost";
$response=array();
$con=mysqli_connect($host,$user,$password,$database)or die("Unable to connect");
if($_SERVER["REQUEST_METHOD"]=="POST"){
if(isset($_POST['OrderSummary'])){
$data=$_POST['OrderSummary'];
$file='text.txt';
$result=file_put_contents($file,$data);
$response["success"]=1;
$response["message"]="done";
}else{
$response["success"]=0;
$response["message"]="parameters not correctly formatted";
}
echo json_encode($response);
}
?>
what changes I can do here, so I can read the data store it in the database?
First, you need to set up a database and a table in a database server (MySQL).
Then you can create an insert statement like below, bind its parameters and execute it.
if (!($statement = $con->prepare('INSERT INTO `your_table` (`OrderSummary`) VALUES (?)'))) {
die('Could not prepare statement: (' . $con->errno . ') ' . $con->error);
}
if (!$statement->bind_param('s', $_POST['OrderSummary'])) {
die('Could not bind parameter: (' . $statement->errno . ') ' . $statement->error);
}
if (!$statement->execute()) {
die('Could not execute statement: (' . $statement->errno . ') ' . $statement->error);
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So I've been at this for a while now and anything I do or research turns up more errors. I keep getting this error: Fatal error: Call to a member function query() on a non-object with code that looks like this. the pic column is for a profile picture directory they uploaded.
$newTarget_file = "uploads/picture.png"
....
$sql = "UPDATE users SET pic='$newTarget_file' WHERE username=:username";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
also this is a php that is submited to that saves the picture they upload and the directory is the $newTarget_file . This is realy frustrating my on how I do this. Thanks in advance for the help.
Basically I want to update the pic column where username=:username with a variable I have already $newTarget_file . what do I do?
As others have said, the error is because your connection object doesn't exist.
Fatal error: Call to a member function query() on a non-object
Based on the tutorial you are following, have you implemented this?
$conn = new mysqli($servername, $dbuser, $dbpw, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
You should have gotten a connection error before the query ever tried to run. Also, as Michael pointed out, you can't used named parameters with mysqli. It's only supported in PDO, but you can still use placeholders. Your new code should look something like this.
if (!($stmt = $conn->prepare("UPDATE users SET pic=? WHERE username=?"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
exit;
}
if (!$stmt->bind_param("ss", $newTarget_file, $username)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
exit;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
exit;
}
$stmt->close();
CREATE DATABASE 'some database name' ;
Works as expecting using mysql's client.
The same query (different database name) from php/mysqli - fails kind of.
It writes to the INFORMATION_SCHEMA.SCHEMATA
But fails to write to the mysql.db table?
This is actually an issue of a larger problem.
What is going on. Why does my mysqli fail?
code:
$mysqli = new mysqli("p:127.0.0.1", "root", "showtech123", "mysql");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if(!$mysqli->query( "CREATE DATABASE $database_name;"))
{echo "DATABASE encountered error:" . $mysqli->error . "<br /";}
Errors:
db_name: terarydatabase3333, un:teraryuser5999
Warning: mysqli::query(): MySQL server has gone away in /www/admin.showtechllc.com/public_html/adddb.php on line 21
Warning: mysqli::query(): Error reading result set's header in /www/admin.showtechllc.com/public_html/adddb.php on line 21
USER encountered error:MySQL server has gone away
the fourth parameter in the constructor is the database you want to use.
you're actually trying to create a new database inside an existing one.
try this :
$mysqli = new mysqli("p:127.0.0.1", "root", "showtech123");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}else{
echo "connected";
}
if(!$mysqli->query( "CREATE DATABASE $database_name;")){
echo "DATABASE encountered error:" . $mysqli->error . "<br /";
}else{
echo $database_name . "created";
}
I have two blocks of code in the body section of an html ( .php) document. The code block before my heading executes, but the block after the heading does not. I've tried phpinfo(); in the first block and it runs fine. Try it in the second block and it doesn't. I have no idea why this could be. If anyone has suggestions I'm all ears.
I'm currently running xampp on a windows machine.
<body>
<?php
if (isset($_SESSION['ProfileID'])){
echo "<div style='text-align: right'>"
. "<a href='CZSN_Login.php'>Log "
. "Out</a></div>\n";
}
//here phpinfo() executes
?>
<h1>Chinese Zodiac Social Network</h1>
<?php
require_once("Includes/inc_ChineseZodiacDB.php");
//here phpinfo() will not execute
if (isset($_SESSION['ProfileID'])){
echo "<h2>Member Pages</h2>\n";
echo"<p>Below is a list of the members of the Chinese Zodiac Social"
. "Network. Click on a member's name to view that member's detailed information"
. "You may also choose to <a href='CZSN_MyProfile.php'>update your profile</a>.</p>\n";
$SQLQuery="select first_name, last_name, user_name "
. "from zodiac_profiles order by "
. "last_name, first name, user_name;";
$result=$DBConnect->query($SQLQuery);
if ($result===false){
echo $ErrorMsgs[];
}
else{
//This should never happen, but we can check anyway.
if ($result->num_rows==0){
echo "<p>There are no members to show.</p>\n";
}
Here is the code in my inc_ChineseZodiacDB.php file:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Try searching in require_once ("Includes / inc_ChineseZodiacDB.php"); there can be triggered die() or exit();
I guess you get "Error headers already sent", because of the title <h1>Chinese Zodiac Social Network</h1>. For phpinfo() to work there shouldn't be any output yet.
You are closing the php tag in the inc_ChineseZodiacDB file (i.e. you have ?> at the end of that file).
When your first file reads in the inc_ChineseZodiacDB file and sees the ?>, it interprets that as the end of your php section of code, and all the other code after require_once("Includes/inc_ChineseZodiacDB.php"); is ignored and read as regular html.
Remove that line, and your problem should be fixed:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
I figured out the ultimate problem. in the include file it reads:
<?php
$ErrorMsgs = array();
$DBConnect = #new msqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
where it should read:
<?php
$ErrorMsgs = array();
$DBConnect = #new mysqli("localhost", "root", "password", "chinese_zodiac");
if ($DBConnect->connect_error)
$ErrorMsgs[] = "The database server is not available."
. "Connect Error is "
. $mysqli->connect_errno
. " " . $mysqli->connect_error . ".";
?>
Note, I was calling msqli rather than mysqli. One simple typo...I'm still not understanding why the error messages were not being thrown for calling an undefined function. I added error_reporting(E_ALL); and ini_set('display_errors', 1); to the top of the file as well, and still no errors thrown. Either way, it works now. Thank you to everyone for the assistance.
I must be doing something wrong in this code....
<?
$codeid=$_GET["codeid"];
$tablecode=$_GET["tablecode"];
$description=$_GET["description"];
$code=$_GET["code"];
$groupcode=$_GET["groupcode"];
$t1=$_GET["t1"];
$t2=$_GET["t2"];
$t3=$_GET["t3"];
$mysqli = new mysqli(dbhost,dbuser,dbpass,dbc);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$q="call spUpdateCodeTable(?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($q);
$stmt->bind_param($codeid,$tablecode,$description,$code,$groupcode,$t1,$t2,$t3);
$stmt->execute();
mysql_close($mysqli);
?>
Absolutely nothing happens...no error message or any other indication of a problem. It just does not run the procedure. (it's an update/insert routine).
I am using this URL...
updateCodeTable.php?codeid=0&codetable=TABLE&desription=testing2%20entry&code=TEST1&groupcode=gcode&t1=t1&t2=t2&t3=t3
...but, if I run the this query in phpMyAdmin, it runs perfectly....
call spUpdateCodeTable(0,'TABLE','testing2','TEST1','group','','','');
I could include the stored procedure code, but it runs fine anytime I run it directly, but just not running successfully from my php code.
Each mysqli* function/method can fail. Either test the return values and/or switch the reporting mechanism to exceptions, see http://docs.php.net/mysqli-driver.report-mode
<?php
// probably better done with http://docs.php.net/filter but anyway ...just check whether all those parameters are really there
// you are positive that GET is the correct method for this action?
if ( !isset($_GET["codeid"], $_GET["tablecode"], $_GET["description"], $_GET["code"], $_GET["groupcode"], $_GET["t1"], $_GET["t2"], $_GET["t3"]) ) {
// die() is such a crude method
// but bare me, it's just an example....
// see e.g. http://docs.php.net/trigger_error
die('missing parameter');
}
else {
$mysqli = new mysqli(dbhost,dbuser,dbpass,dbc);
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
}
$q="call spUpdateCodeTable(?,?,?,?,?,?,?,?)";
$stmt = $mysqli->prepare($q);
if ( !$stmt ) {
// $mysqli->error has more info
die('prepare failed');
}
// you have to provide the format of each parameter in the first parameter to bind_param
// I just set them all to strings, better check that
if ( !$stmt->bind_param('ssssssss', $_GET['codeid'], $_GET['tablecode'], $_GET['description'], $_GET['code'], $_GET['groupcode'], $_GET['t1'], $_GET['t2'], $_GET['t3']) ) {
// $stmt->error has more info
die('bind failed');
}
if ( !$stmt->execute() ) {
// $stmt->error has more info
die('execute failed');
}
}
May you have a try to this?
mysqli->query("call spUpdateCodeTable($codeid,'$tablecode',
'$description','$code','$groupcode','$t1','$t2','$t3')");