1

I want to use a single database connection with multiple queries but use prepare and bind_param. How can i do this? I cant find it in the documentation.

Edit: i want two completely different queries.

$db = getConnection();
$query = "INSERT INTO talks(title, body, topic) VALUES(?, ?, ?)";
$stmt = $db->prepare($query);
$stmt->bind_param('sss', $title , $body, $topic);
$stmt->execute();
$stmt->close();

$query = "SELECT * WHERE title=?";
$stmt = $db->prepare($query);
$stmt->bind_param("s", $title);
$stmt->execute();
$stmt->bind_result($i, $t, $b, $to);
$stmt->fetch();
$id = $i;
$stmt->close();

Its telling me that $stmt isnt an object on the second go around

  • You want the same query with different parameters? Or an entirely different query? – Madara's Ghost Nov 26 '12 at 21:45
  • Possible duplicate off: http://stackoverflow.com/questions/11632902/mysqli-can-it-prepare-multiple-queries-in-one-statement – RTB Nov 26 '12 at 21:47

1 Answers1

2

Just prepare a second query, as you did with the first.

$conn = new mysqli(....);
$stmt = $conn->prepare(....);
//Do stuff with $stmt

$stmt = $conn->prepare(...different...); //$stmt is overridden with the new query.
//Do stuff with the new $stmt.
Madara's Ghost
  • 165,920
  • 50
  • 255
  • 304
  • see ive been trying this and it is saying that it is an ivalid object. – user1846761 Nov 26 '12 at 21:47
  • I am also facing this strange issue but not able to figure it out. mysql object was not alive any more after one db operation done. Since it ask me to open the connection after performed the first query. – loganathan Aug 06 '13 at 19:03
  • @loganathan: That means your query is invalid. Check for errors. – Madara's Ghost Aug 06 '13 at 19:59
  • I log the query into text file and then i tried to ran that query from the php my admin and from mysql cmd prompt that query executed great. So the only thing is i need to close the connection before i do any mysql operation either update or select or insert. I do not know why it's not keep the db connection as persistence. Am using myqli method to establish the connection with local mysql server – loganathan Aug 07 '13 at 13:18
  • You should ask this as a separate question. See [ask]. – Madara's Ghost Aug 07 '13 at 13:33